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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 23:05:24