初始化 npm 项目
npm init -y
npm install -D typescript ts-node @types/node
添加 tsconfig.json
npx tsc --init
tsconfig.json
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"target": "ES2020",
"sourceMap": true,
"outDir": "dist",
"noImplicitAny": true
},
"include": ["src/**/*"]
}
安装 nodemon,监听文件修改自动重启应用程序
npm install -D nodemon
根目录新建文件 nodemon.json
{
"watch": ["src"],
"ext": "ts",
"ignore": ["src/**/*.spec.ts"],
"exec": "ts-node ./src/index.ts"
}
修改 package.json 中的 scripts
"scripts": {
"start": "nodemon",
"build": "tsc"
},
安装和配置 express
npm install express dotenv
npm install -D @types/express
src/index.ts
import express from "express";
import dotenv from "dotenv";
dotenv.config();
const app = express();
app.get("/", (req, res) => {
res.send("Hello World!!!");
});
app.listen(process.env.PORT, () => {
console.log(`Server listening on port ${process.env.PORT}`);
});
.env
PORT=3000
通过 npm run dev
启动开发环境,通过 npm run build && node dist/index.js
启动生产环境