首先,創(chuàng)建一個(gè)新的項(xiàng)目目錄,并初始化 npm 項(xiàng)目:
mkdir my-nodejs-backend
cd my-nodejs-backend
npm init -y
我們需要安裝一些基本的依賴,包括 express(一個(gè)常用的 Node.js 框架)、typescript、ts-node(用于直接運(yùn)行 TypeScript 文件)、@types/express(Express 的類型定義)以及 @types/node(Node.js 的類型定義):
npm install express typescript ts-node @types/express @types/node --save
此外,為了更方便地管理開發(fā)依賴,我們可以安裝 nodemon 和 tsconfig-paths:
npm install nodemon tsconfig-paths --save-dev
在項(xiàng)目根目錄下創(chuàng)建一個(gè) tsconfig.json 文件,配置 TypeScript:
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": "./",
"paths": {
"*": ["src/*"]
}
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
src/app.ts
這個(gè)文件將包含 Express 應(yīng)用的配置:
import express from 'express';
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Hello, World!');
});
export default app;
src/index.ts
這個(gè)文件是應(yīng)用的入口點(diǎn):
import app from './app';
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
在項(xiàng)目根目錄下創(chuàng)建一個(gè) nodemon.json 文件,配置 nodemon:
{
"watch": ["src"],
"ext": "ts",
"exec": "ts-node ./src/index.ts"
}
在 package.json 中添加一些方便的開發(fā)腳本:
"scripts": {
"start": "nodemon",
"build": "tsc",
"serve": "node dist/index.js"
}