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

如何在Nest中导入仅支持ES Module的包?动态import()无效求助

在Nest中正确导入仅支持ES Module的包

问题根源

你虽然在代码中使用了动态import(),但当前Nest项目默认编译为CommonJS格式,编译后的bootstrap.js仍会用require()加载ESM包,触发Node.js的ERR_REQUIRE_ESM错误。

解决方案

方案一:将项目切换为ES Module模式(推荐)

这是适配纯ESM包最彻底的方式:

  1. 在项目根目录的package.json中添加:
    "type": "module"
    
  2. 修改tsconfig.json配置:
    {
      "compilerOptions": {
        "module": "ESNext",
        "moduleResolution": "NodeNext",
        "target": "ES2020",
        "outDir": "./dist",
        "esModuleInterop": true,
        "skipLibCheck": true,
        "strict": true
      }
    }
    
  3. 更新nest-cli.json的编译配置:
    {
      "$schema": "https://json.schemastore.org/nest-cli",
      "collection": "@nestjs/schematics",
      "sourceRoot": "src",
      "compilerOptions": {
        "deleteOutDir": true,
        "module": "ESNext"
      }
    }
    
  4. 调整启动脚本(适配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():

  1. 修改tsconfig.json:
    {
      "compilerOptions": {
        "module": "CommonJS",
        "moduleResolution": "Node",
        "target": "ES2020", // 需至少ES2020支持动态import
        "outDir": "./dist",
        "esModuleInterop": true,
        "skipLibCheck": true,
        "strict": true,
        "allowSyntheticDefaultImports": true
      }
    }
    
  2. 使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 18:22:43