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

TypeScript 5.0如何实现.ts后缀导入并编译至dist目录?

实现.ts后缀导入同时编译生成dist目录的解决方案

核心问题分析

当前配置里的noEmit: true是无法生成dist文件的直接原因,但直接关闭它的话,allowImportingTsExtensions会让编译后的文件保留.ts后缀——而dist目录里只有编译后的.js文件,导致Node.js运行时找不到对应文件。

可行方案:拆分tsconfig配置

通过两份配置分别处理开发和生产场景,既满足开发时导入.ts源文件的需求,又保证编译产物的可执行性。

1. 配置开发用tsconfig.dev.json

这份配置用于开发阶段的类型检查、ts-node运行,保留.ts后缀导入支持:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "noEmit": true,
    "allowImportingTsExtensions": true
  }
}

2. 调整生产编译用tsconfig.json

移除noEmit和allowImportingTsExtensions,让TypeScript自动处理导入后缀转换:

{
  "compilerOptions": {
    "lib": ["es2020"],
    "module": "NodeNext",
    "experimentalDecorators": true,
    "moduleResolution": "node16",
    "sourceMap": true,
    "target": "es2020",
    "noImplicitAny": false,
    "typeRoots": ["node_modules/@types"],
    "outDir": "dist",
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "removeComments": true
  },
  "include": ["src"],
  "exclude": ["node_modules/**/*"],
  "ts-node": {
    "files": true
  }
}

3. 配置package.json脚本(可选)

添加便捷命令,区分开发和编译流程:

{
  "scripts": {
    "dev": "ts-node --project tsconfig.dev.json src/index.ts",
    "build": "tsc -p tsconfig.json",
    "type-check": "tsc -p tsconfig.dev.json"
  }
}

方案原理

在module: NodeNext和moduleResolution: node16的模式下,TypeScript会严格遵循ESM导入规则:

  • 开发阶段(使用tsconfig.dev.json):允许直接导入.ts后缀的源文件,仅做类型检查不生成产物。
  • 编译阶段(使用tsconfig.json):自动将源码中所有.ts后缀的导入路径替换为.js,确保dist目录下的产物能被Node.js正确加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 23:25:33