在NX Monorepo中使用ts-node解决‘Cannot find module’报错
解决NX Monorepo中ts-node无法识别内部包的问题
核心原因
ts-node默认不会自动加载NX Monorepo的路径别名配置,且未确保依赖包已提前构建,导致找不到@project/myplugin模块。
具体解决方案
1. 让ts-node识别NX路径别名
首先安装tsconfig-paths依赖,用于解析tsconfig中的路径映射:
npm install -D tsconfig-paths # 或 yarn add -D tsconfig-paths # 或 pnpm add -D tsconfig-paths
修改project.json中ui目标的命令,指定tsconfig并启用路径解析:
"ui": { "executor": "nx:run-commands", "options": { "commands": ["ts-node -r tsconfig-paths/register --project tsconfig.json src/compile-ui.ts"], "cwd": "./apps/vendure" }, "dependsOn": ["^build"] }
-r tsconfig-paths/register:注册路径解析器,让ts-node识别tsconfig中的paths配置--project tsconfig.json:指定使用项目的tsconfig文件,确保读取到NX的路径映射
2. 确保依赖包已提前构建
将dependsOn的值从["build"]改为["^build"]:
build仅构建当前应用^build会构建当前应用所有依赖的NX包(包括@project/myplugin),确保ts-node运行时能找到已编译的模块
3. 验证tsconfig路径配置
检查项目根目录的tsconfig.base.json,确认包含正确的路径映射:
"compilerOptions": { // ...其他配置 "paths": { "@project/myplugin": ["packages/myplugin/src/index.ts"] } }
同时确保apps/vendure/tsconfig.json中extends了根目录的tsconfig.base.json:
{ "extends": "../../tsconfig.base.json", // ...其他配置 }
4. 备选方案:直接运行编译后的脚本
如果上述方法仍有问题,可先编译compile-ui.ts,再运行生成的js文件:
- 修改
ui目标的dependsOn添加当前应用的build:["^build", "build"] - 命令改为:
node dist/apps/vendure/src/compile-ui.js - 调整
compile-ui.ts中的路径,确保outputPath指向正确位置(比如使用绝对路径或基于dist的相对路径)
内容的提问来源于stack exchange,提问作者Stefan
相关产品推荐
相关产品推荐

