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

创建ts-node ESM项目遇.ts文件扩展名未知错误,求解决方案

解决ts-node + ESM 下的 "Unknown file extension '.ts'" 错误

核心问题根源

当package.json设置"type": "module"后,Node默认以ESM模式处理文件,但ts-node需要明确的配置对齐ESM规则,同时TypeScript编译选项也要和ESM模式匹配,否则会出现文件扩展名解析错误。

具体修复步骤

1. 调整tsconfig.json配置

修改主配置文件,确保模块解析规则和ts-node的ESM适配:

{
    "extends": "./tsconfig.node20.json",
    "compilerOptions": {
        "module": "ESNext",
        "moduleResolution": "Bundler",
        "outDir": "./dist",
        "allowImportingTsExtensions": true,
        "noEmit": true
    },
    "include": ["./src/**/*"],
    "ts-node": {
        "esm": true,
        "experimentalSpecifierResolution": "node"
    }
}

2. 修正package.json的dev脚本

给ts-node添加必要参数,指定配置文件:

{
  // 其他配置保持不变
  "scripts": {
    "compile": "tsc",
    "dev": "ts-node --esm --project tsconfig.json src/index.ts"
  },
  // 其他配置保持不变
}

3. 优化基础tsconfig配置(可选)

修改tsconfig.node20.json,让基础配置更适配ESM:

{
  "$schema": "https://json.schemastore.org/tsconfig",
  "display": "Node 20",
  "_version": "20.1.0",

  "compilerOptions": {
    "lib": ["ES2022"],
    "module": "ESNext",
    "target": "es2022",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "Bundler"
  }
}

验证修复

执行npm run dev,此时应该能正常输出hi,文件扩展名错误会被解决。

关键配置说明

  • allowImportingTsExtensions:让TypeScript允许导入带.ts后缀的文件,ts-node在ESM模式下依赖此配置解析模块
  • --experimental-specifier-resolution=node:解决Node ESM模式下对文件扩展名的严格校验问题,帮助ts-node识别.ts文件
  • noEmit:dev模式下ts-node实时编译执行,无需生成编译产物,可提升运行效率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 09:27:41