如何在 Node.js 和 Express 中设置 TypeScript(2023)

2025-06-08

如何在 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
Enter fullscreen mode Exit fullscreen mode

初始化 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"
}
Enter fullscreen mode Exit fullscreen mode

2. 安装 TypeScript 和其他依赖项

npm install express mongoose cors mongodb dotenv
Enter fullscreen mode Exit fullscreen mode
npm install  -D typescript ts-node-dev @types/express @types/cors
Enter fullscreen mode Exit fullscreen mode

3.生成tsconfig.json

npx tsc --init
Enter fullscreen mode Exit fullscreen mode

上述命令将生成一个名为 tsconfig.json 的新文件,其中包含以下默认编译器选项:

target: es2016
module: commonjs
strict: true
esModuleInterop: true
skipLibCheck: true
forceConsistentCasingInFileNames: true
Enter fullscreen mode Exit fullscreen mode

打开 tsconfig.json 文件后,你会看到许多其他被注释掉的编译器选项。在 tsconfig.json 中,compilerOptions 是必须指定的字段。

  • 将 rootDir 和 outDir 设置为 src 和 dist 文件夹
{
  "compilerOptions": {
    "outDir": "./dist"

    // other options remain same
  }
}
Enter fullscreen mode Exit fullscreen mode

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}`);
});

Enter fullscreen mode Exit fullscreen mode

5. 观察文件变化并构建目录

npm install  nodemon

Enter fullscreen mode Exit fullscreen mode

安装这些开发依赖项后,更新 package.json 文件中的脚本:

{

  "scripts": {
    "build": "npx tsc",
    "start": "node dist/index.js",
    "dev": "nodemon index.ts"
  }
}

Enter fullscreen mode Exit fullscreen mode

6.运行代码

npm run dev 

Enter fullscreen mode Exit fullscreen mode

如果一切顺利,您将在http://localhost:8000 的
控制台中看到 Server is Fire 的消息

鏂囩珷鏉ユ簮锛�https://dev.to/cristain/how-to-set-up-typescript-with-nodejs-and-express-2023-gf
PREV
成为一名成功的开发顾问所需的 14 项技能
NEXT
这不是魔法,这是 Webpack。捆绑器 那么,Webpack 是什么?构建依赖关系图摘要