如何在 Node.js 和 Express 中设置 TypeScript(2023)
在本文中,我们将介绍在 Express 应用程序中设置 TypeScript 的最佳方法,并了解随之而来的基本限制。
目录
- 创建 package.json 文件
- 安装 TypeScript 和其他依赖项
- 生成 tsconfig.json
- 创建带有 .ts 扩展名的 Express 服务器
- 观察文件变化并构建目录
1.创建初始文件夹和package.json
mkdir node-express-typescript
cd node-express-typescript
npm init --yes
初始化 package.json 文件后,新创建的文件可能类似于以下代码:
{
"name": "Your File Name",
"version": "1.0.0",
"description": "",
"main": "index.js", // Entry Point change it from js to .ts
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"type": "module",
"keywords": [],
"author": "",
"license": "ISC"
}
2. 安装 TypeScript 和其他依赖项
npm install express mongoose cors mongodb dotenv
npm install -D typescript ts-node-dev @types/express @types/cors
3.生成tsconfig.json
npx tsc --init
上述命令将生成一个名为 tsconfig.json 的新文件,其中包含以下默认编译器选项:
target: es2016
module: commonjs
strict: true
esModuleInterop: true
skipLibCheck: true
forceConsistentCasingInFileNames: true
打开 tsconfig.json 文件后,你会看到许多其他被注释掉的编译器选项。在 tsconfig.json 中,compilerOptions 是必须指定的字段。
- 将 rootDir 和 outDir 设置为 src 和 dist 文件夹
{
"compilerOptions": {
"outDir": "./dist"
// other options remain same
}
}
4.创建一个带有.ts扩展名的Express服务器
创建一个名为 index.ts 的文件名,打开它
import express, { Express, Request, Response , Application } from 'express';
import dotenv from 'dotenv';
//For env File
dotenv.config();
const app: Application = express();
const port = process.env.PORT || 8000;
app.get('/', (req: Request, res: Response) => {
res.send('Welcome to Express & TypeScript Server');
});
app.listen(port, () => {
console.log(`Server is Fire at http://localhost:${port}`);
});
5. 观察文件变化并构建目录
npm install nodemon
安装这些开发依赖项后,更新 package.json 文件中的脚本:
{
"scripts": {
"build": "npx tsc",
"start": "node dist/index.js",
"dev": "nodemon index.ts"
}
}
6.运行代码
npm run dev
如果一切顺利,您将在http://localhost:8000 的
控制台中看到 Server is Fire 的消息