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

TS编译生成的index.js无法找到自定义模块问题求助

解决ES模块下TypeScript编译后找不到本地模块的问题

问题原因

你的项目在package.json中设置了"type": "module",启用了ES模块规范。Node.js处理ES模块时,要求本地文件导入必须指定完整文件扩展名(比如.js),但TypeScript默认编译时不会为相对路径的导入自动添加.js后缀,导致生成的dist/index.js中import graphqlServer from './server/graphql'无法找到实际存在的graphql.js文件。

解决方案

方案1:调整TypeScript配置,自动添加扩展名

修改tsconfig.json的compilerOptions,将module和moduleResolution设置为适配ES模块的选项:

{
  "compilerOptions": {
    "target": "es2020",
    "module": "nodenext", // 或"bundler",根据Node版本选择
    "moduleResolution": "nodenext",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "resolveJsonModule": true,
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,
    "lib": ["esnext"],
    "baseUrl": ".",
    "paths": {
      "*": ["node_modules/*", "src/types/*"]
    }
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules", "dist"]
}
  • module: "nodenext"会让TS根据package.json的type字段生成对应模块格式的代码,并自动添加正确的文件扩展名。
  • 编译后检查dist/index.js,导入路径会变成import graphqlServer from './server/graphql.js',Node就能正确定位文件。

方案2:手动在TS源码中添加扩展名

在TypeScript源码的导入语句中直接添加.ts扩展名(TS编译时会自动替换为.js):

// src/index.ts
import graphqlServer from './server/graphql.ts';
import db from './config/db.ts';

这种方式无需修改tsconfig,但需要确保所有本地导入都补上扩展名。

方案3:使用Node.js实验性加载器(不推荐)

通过--experimental-specifier-resolution=node启动参数让Node.js允许不带扩展名的导入,但这是实验性特性,不建议生产环境使用:

node --experimental-specifier-resolution=node dist/index.js

验证

重新编译项目后,查看dist/index.js中的导入语句是否带有.js后缀,运行项目确认错误消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 18:18:13