如何在Nest中导入仅支持ES Module的包?动态import()无效求助
在Nest中正确导入仅支持ES Module的包
问题根源
你虽然在代码中使用了动态import(),但当前Nest项目默认编译为CommonJS格式,编译后的bootstrap.js仍会用require()加载ESM包,触发Node.js的ERR_REQUIRE_ESM错误。
解决方案
方案一:将项目切换为ES Module模式(推荐)
这是适配纯ESM包最彻底的方式:
- 在项目根目录的
package.json中添加:"type": "module" - 修改
tsconfig.json配置:{ "compilerOptions": { "module": "ESNext", "moduleResolution": "NodeNext", "target": "ES2020", "outDir": "./dist", "esModuleInterop": true, "skipLibCheck": true, "strict": true } } - 更新
nest-cli.json的编译配置:{ "$schema": "https://json.schemastore.org/nest-cli", "collection": "@nestjs/schematics", "sourceRoot": "src", "compilerOptions": { "deleteOutDir": true, "module": "ESNext" } } - 调整启动脚本(适配ESM运行):
在package.json的scripts中修改生产启动命令:
开发环境可使用"start:prod": "node dist/main.js"tsx实现热重载:
安装依赖:"start:dev": "tsx watch src/main.ts"pnpm add tsx -D
方案二:保持CommonJS模式,调整编译行为
若不想切换项目模块类型,可通过配置确保动态import()不被转为require():
- 修改
tsconfig.json:{ "compilerOptions": { "module": "CommonJS", "moduleResolution": "Node", "target": "ES2020", // 需至少ES2020支持动态import "outDir": "./dist", "esModuleInterop": true, "skipLibCheck": true, "strict": true, "allowSyntheticDefaultImports": true } } - 使用
tsx或ts-node/esm运行项目,避免编译时转换动态import:
开发启动命令改为:"start:dev": "tsx watch src/main.ts"
方案三:降级到兼容CommonJS的包版本
如果配置调整成本过高,可选择支持CommonJS的包版本,比如chalk@4(同时兼容ESM和CommonJS):
pnpm add chalk@4
之后即可直接使用静态导入:
import chalk from 'chalk';
内容的提问来源于stack exchange,提问作者Henry
相关产品推荐
相关产品推荐

