如何在TypeScript中使用绝对路径导入本地ES6模块?
解决ts-node环境下ES6模块绝对路径导入问题
1. 修复tsconfig.json语法错误并配置路径映射
你的tsconfig存在两处语法错误:compilerOptions最后一个属性末尾多了逗号,include前缺少逗号。同时需要明确配置paths来映射绝对路径,修正后的配置如下:
{ "compilerOptions": { "lib": ["ES6"], "target": "ES6", "baseUrl": "./", "rootDir": "src", "esModuleInterop": true, "moduleResolution": "node", "paths": { "src/*": ["src/*"] } }, "include": ["src/**/*.ts"], "exclude": ["node_modules"] }
2. 让ts-node识别路径映射
ts-node默认不支持解析tsconfig.json中的paths配置,需要安装tsconfig-paths来处理:
- 安装依赖:
npm install -D tsconfig-paths - 修改启动命令,添加
-r tsconfig-paths/register参数:ts-node -r tsconfig-paths/register src/index.ts - 或者在
package.json的scripts中配置启动脚本:"scripts": { "start": "ts-node -r tsconfig-paths/register src/index.ts" }
3. ES模块模式下的额外配置
如果你的项目启用了ES模块(package.json中设置了"type": "module"),需要调整两处配置:
- 修改
tsconfig.json的module选项为ESNext:"compilerOptions": { // ...其他配置 "module": "ESNext" } - 启动命令加上
--esm参数:ts-node --esm -r tsconfig-paths/register src/index.ts
注意事项
- 不要同时使用
module-alias和tsconfig-paths,避免配置冲突 - 确保所有导入路径和
paths配置的规则匹配,比如src/my-module对应src/my-module.ts文件存在
内容的提问来源于stack exchange,提问作者Elytes
相关产品推荐
相关产品推荐

