NestJS项目中无法导入ESM模块的问题求助
解决Nest.js + TypeScript 无法导入ESM模块的问题
核心问题排查与修复步骤
1. 修正TypeScript模块解析配置
你的tsconfig.json中module设为NodeNext,但moduleResolution仍为Node,两者不匹配会导致ESM模块解析失败,需修改为:
{ "compilerOptions": { "lib": ["ES2020"], "esModuleInterop": true, "module": "NodeNext", "moduleResolution": "NodeNext", // 关键修改:与module保持一致 "declaration": true, "removeComments": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "allowSyntheticDefaultImports": true, "target": "esnext", "sourceMap": true, "outDir": "./dist", "baseUrl": "./", "incremental": true, "skipLibCheck": true, "strictNullChecks": false, "noImplicitAny": false, "strictBindCallApply": false, "forceConsistentCasingInFileNames": false, "noFallthroughCasesInSwitch": false, "resolveJsonModule": true // 新增:支持导入JSON模块(可选但实用) } }
2. 调整ts-node启动参数
ts-node默认以CommonJS模式运行,需显式启用ESM支持,修改package.json的启动脚本:
{ "scripts": { "start": "ts-node --esm src/main.ts", "start:dev": "ts-node-dev --esm src/main.ts" } }
如果使用Nest CLI,需在nest-cli.json中配置webpack支持ESM:
{ "compilerOptions": { "webpack": true, "tsConfigPath": "./tsconfig.json" } }
3. 修复导入语法错误
你提供的示例代码中导入语句使用了反引号,这是语法错误,需改为单/双引号:
// 错误写法 import random from `random`; // 正确写法 import random from 'random';
4. 处理文件扩展名要求
启用type:module和NodeNext后,导入本地模块时需添加.js扩展名(TypeScript编译时会自动处理,但开发阶段必须写对):
import { OtherService } from './other.service.js';
5. 切换到Node.js LTS版本
Node.js 19为非LTS版本,存在部分ESM兼容问题,建议切换到18.x LTS版本:
nvm install 18 nvm use 18
6. 验证依赖兼容性
确保所有依赖包兼容ESM:
- Nest.js 9+已原生支持ESM,你的版本9.2.1没问题
- 升级
ts-loader到最新版(当前9.4.2可升级至10.x)以确保Webpack ESM支持
内容的提问来源于stack exchange,提问作者alexzedim
相关产品推荐
相关产品推荐

