Node命令中无法导入模块问题求助
问题描述
我在package.json中配置了npm命令:
"create-new": "node --no-warnings --loader ts-node/esm tools/createNewCommand.ts"
运行该命令时,代码尝试从src目录导入模块(如import xxx from '@/main.js'),会触发错误:
CustomError: Cannot find package '@/main.js'
以下是我的配置文件:
tsconfig.json
{ "compilerOptions": { "target": "ESNext", "module": "NodeNext", "moduleResolution": "NodeNext", "typeRoots": ["@types", "./node_modules/@types"], "resolveJsonModule": true, "baseUrl": ".", "paths": { "@/*": ["src/*"] }, "allowJs": true, "outDir": "dist", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "strictPropertyInitialization": false }, "ts-node": { "swc": true }, "include": ["src/**/*", "tools/**/*"] }
.swcrc
{ "jsc": { "parser": { "syntax": "typescript", "tsx": false, "decorators": true, "dynamicImport": true }, "target": "esnext", "paths": { "@routes/*": ["./src/routes/*"], "@middlewares/*": ["./src/middlewares/*"], "@/*": ["./src/*"] }, "baseUrl": ".", "experimental": { "keepImportAssertions": true } }, "module": { "type": "nodenext" } }
解决方法
问题核心是ES模块模式下,ts-node默认不会自动解析tsconfig中的paths别名,结合你使用swc的场景,可通过以下方式修复:
- 调整ts-node配置
在tsconfig.json的ts-node字段中添加ES模块支持和路径解析开关,让ts-node识别别名规则:
"ts-node": { "swc": true, "esm": true, "paths": true }
- 补充package.json的exports规则
由于使用了NodeNext模块系统,Node.js会优先读取package.json的exports配置,添加以下内容让Node识别@别名:
"exports": { "@/*": "./src/*" }
- 替换为tsx工具(最简方案)
如果上述配置仍有问题,直接用tsx替代ts-node,它默认支持tsconfig的paths解析,无需额外配置:- 安装tsx:
npm install -D tsx - 修改npm命令:
- 安装tsx:
"create-new": "tsx --no-warnings tools/createNewCommand.ts"
- 检查导入后缀
ES模块模式下Node.js要求导入必须带完整文件后缀(如.js/.ts),确保导入路径后缀正确;也可在tsconfig中添加"allowImportingTsExtensions": true,同时在swcrc中对应配置支持该特性。
内容的提问来源于stack exchange,提问作者user19210100
相关产品推荐
相关产品推荐

