You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确配置TypeScript Node.js项目?含模块规范与tsconfig设置

TypeScript开发Node.js:ES模块配置与模块规范指南

一、模块规范选择:ES6 vs CommonJS

  • 优先选ES6模块(ESM):Node.js从v12开始全面支持ESM,配合TypeScript的import/export语法,能完美适配VS Code的自动补全和类型提示,这也是实现import express from 'express'写法的基础。
  • 若依赖大量旧版CommonJS包:无需纠结,esModuleInterop配置已处理兼容问题,ESM下可直接导入CommonJS模块。

二、tsconfig.json 优化配置

你的现有配置已接近最优,只需补充关键配置并调整细节:

{
  "exclude": ["node_modules"],
  "include": ["src/**/*"], // 指定代码目录,让TS自动扫描编译
  "compilerOptions": {
    "target": "ES6",
    "module": "ES6",
    "moduleResolution": "node",
    "outDir": "dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "resolveJsonModule": true, // 支持导入JSON文件
    "allowImportingTsExtensions": false // 避免导入时写.ts后缀,编译后自动转.js
  }
}

核心必加步骤:在项目根目录的package.json中添加type字段,告诉Node.js识别ESM:

{
  "type": "module"
}

缺少这个配置,编译后的.js文件会被当作CommonJS处理,直接导致运行报错。

三、正确的导入/导出写法

导入示例

  • 第三方包:
import express from 'express';
import { Router } from 'express';
  • 本地模块:
// 导入默认导出
import myFunc from './utils/myFunc';
// 导入具名导出
import { formatDate, calculateSum } from './utils/tools';

导出示例

  • 默认导出(一个文件仅能有一个):
// utils/myFunc.ts
export default function add(a: number, b: number): number {
  return a + b;
}
  • 具名导出(支持多个):
// utils/tools.ts
export function formatDate(date: Date): string {
  return date.toLocaleDateString();
}

export const calculateSum = (nums: number[]): number => nums.reduce((a, b) => a + b, 0);

四、VS Code自动补全注意事项

  • 安装对应包的类型声明:比如express的类型包@types/express,执行npm install -D @types/express即可。
  • 若自动补全失效,重启VS Code的TypeScript语言服务:快捷键Ctrl+Shift+P,选择"TypeScript: Restart TS Server"。

内容的提问来源于stack exchange,提问作者swftowu69

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 01:35:16