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

NX monorepo中Node/TS项目编译后运行报错:目录导入不支持

解决NX Monorepo中Node.js应用的模块导入错误

问题根源分析

你的问题核心在于两个点:

  1. 模块系统不匹配:你的api应用编译后保留了ES模块的import语法,而参考应用被转换为CommonJS的require,Node处理ES模块的目录导入规则更严格,导致Directory import错误。
  2. 相对路径解析问题:直接导入../config/config找不到模块,大概率是TypeScript路径配置或NX构建路径映射的问题。

分步解决方案

1. 统一TypeScript模块配置为CommonJS

对比参考应用的tsconfig.app.json,修改apps/api/tsconfig.app.json的编译选项:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "CommonJS",
    "moduleResolution": "Node10",
    "outDir": "../../dist/apps/api",
    "rootDir": "."
  },
  "include": ["src/**/*", "config/**/*"]
}
  • 确保module设为CommonJS,这会让TypeScript将import编译为Node兼容的require。
  • moduleResolution设为Node10,匹配CommonJS的解析逻辑。
  • include要包含config/**/*,确保配置文件被编译。

2. 检查并修正NX构建配置

打开apps/api/project.json,确认build目标的配置:

{
  "targets": {
    "build": {
      "executor": "@nx/node:build",
      "options": {
        "main": "apps/api/src/main.ts",
        "outputPath": "dist/apps/api",
        "tsConfig": "apps/api/tsconfig.app.json",
        "assets": []
      }
    },
    "serve": {
      "executor": "@nx/node:serve",
      "options": {
        "buildTarget": "api:build"
      }
    }
  }
}
  • 确保main指向正确的入口文件,tsConfig指定的是修改后的tsconfig.app.json。
  • outputPath不要嵌套错误,避免编译后路径出现dist/apps/api/apps/api这种重复结构。

3. 修复相对路径导入问题

如果直接用../config/config找不到模块,有两种解决方式:

方式一:使用目录导入并确保index文件正确

确保config/index.ts正确导出config:

// config/index.ts
export { config } from './config';

然后在main.ts中使用:

const { config } = await import('../config');

方式二:配置TypeScript路径别名

在apps/api/tsconfig.app.json中添加路径别名,避免相对路径出错:

"compilerOptions": {
  // ...其他配置
  "paths": {
    "@api/config": ["apps/api/config"]
  }
}

然后导入时使用:

const { config } = await import('@api/config');

4. 清理并重新构建

执行以下命令清理旧产物并重新运行:

nx clean api
nx serve api

5. 检查package.json的"type"字段

如果apps/api目录下有自己的package.json,确保没有设置"type": "module",否则Node会强制按ES模块处理,导致CommonJS编译产物出错。

验证结果

编译完成后,查看dist/apps/api/src/main.js,确认异步导入已被转换为:

const { config } = await Promise.resolve().then(() => require('../config'));

此时Node运行时就不会再出现目录导入的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:46:23