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

引入ESM-only库后,配置type:module的TS项目如何运行dist产物?

解决TypeScript ESM项目构建后运行"exports is not defined"错误

1. 修复tsconfig.json核心配置

你的tsconfig存在关键配置错误,导致编译产物混合了CommonJS语法,同时阻止了新的ESM代码生成:

  • noEmit: true 会禁用TypeScript的编译输出,当前dist目录大概率是旧的CommonJS产物,必须改为false
  • 调整模块解析逻辑,确保输出纯ESM代码

修改后的tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "rootDir": "./src",
    "moduleResolution": "NodeNext",
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"]
    },
    "outDir": "./dist",
    "noEmit": false,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "allowImportingTsExtensions": false
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

2. 替换代码中的CommonJS语法

遍历所有源码文件,将CommonJS导出语法全部替换为ESM格式:

  • 把 module.exports = xxx 改为 export default xxx
  • 把 exports.xxx = yyy 改为 export const xxx = yyy
  • 导入语句必须带显式后缀(ESM要求):比如 import utils from '@/utils.js'

3. 调整package.json配置

  • 更新main字段指向编译后的ESM入口:
    "main": "dist/index.js"
    
  • 确认生产环境启动脚本路径正确:
    "start:prod": "node dist/index.js"
    

4. 重新构建并验证

执行完整构建流程:

npm run build

检查dist目录下的文件,确保所有导出都是ESM的export/export default语法,无exports或module.exports残留。

最后运行生产环境命令:

npm run start:prod

额外注意事项

  • ts-node的--esm参数配置正确,可继续用于开发环境
  • tsc-alias会自动处理路径别名,当前版本支持ESM输出
  • 若仍有路径解析问题,可在tsconfig.json的compilerOptions中添加"extensions": [".js", ".mjs", ".ts"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 09:43:19