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

TypeScript编写的Node.js服务器生产运行报错,求解决方案

解决方案

错误原因分析

第一个错误是因为Node.js默认使用CommonJS模块系统,无法识别ES模块的import语句;添加"type": "module"切换到ES模块模式后,ES模块要求导入必须指定完整文件扩展名(如.js),但TypeScript默认编译时不会自动为导入语句添加扩展名,导致Node.js找不到对应文件。


1. 调整TypeScript编译配置(tsconfig.json)

修改tsconfig.json中的模块解析规则,让TypeScript按照Node.js的ES模块规范生成带扩展名的导入语句:

{
  "compilerOptions": {
    "composite": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": ["node"],
    "paths": {
      "@/*": ["./src/*"]
    },
    "outDir": "dist",
    "allowSyntheticDefaultImports": true,
    "lib": ["ES2020"],
    "module": "ES2020",
    "moduleResolution": "node16", // 替换原有的"node"配置
    "target": "ES2020",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "resolveJsonModule": true // 可选:若需导入JSON文件则添加
  },
  "references": [
    {
      "path": "../ridehub-common"
    }
  ]
}

2. 完善package.json脚本

添加编译命令并修正启动脚本,确保运行编译后的ES模块文件:

{
  "name": "ridehub-server",
  "version": "1.0.0",
  "description": "learning",
  "main": "dist/app.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "tsc", // 添加编译命令
    "start": "node dist/app.js", // 修正为运行编译后的文件
    "dev": "tsx app.ts"
  },
  // 其余依赖配置保持不变
}

3. 编译并启动服务

执行以下命令完成编译和启动:

npm run build
npm start

额外说明

  • 若使用了@/*这类路径别名,生产环境下Node.js的ES模块无法直接识别,可通过以下方式处理:
    1. 安装tsconfig-paths依赖
    2. 修改启动脚本为:"start": "node -r tsconfig-paths/register dist/app.js"
  • 避免使用--experimental-specifier-resolution=node这类实验性参数,不推荐用于生产环境。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 11:36:19