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

如何配置tsconfig强制ESM项目导入必须包含.js扩展名?

解决ESM下TypeScript导入必须带.js扩展名的强制校验问题

一、修改tsconfig.json配置

要让TypeScript在编译阶段就强制校验导入必须带.js扩展名,核心是调整模块解析策略,修改以下配置项:

  1. 将moduleResolution从Node改为NodeNext(或Node16),这会让TypeScript严格遵循Node.js的ESM规范进行模块解析,不带扩展名的导入会直接触发编译错误。
  2. 可选但推荐添加forceConsistentCasingInFileNames,避免文件名大小写导致的解析问题;如果项目中有JSON文件导入,加上resolveJsonModule: true。

修改后的tsconfig.json如下:

{
  "compilerOptions": {
    "module": "ES2022",
    "target": "es2022",
    "moduleResolution": "NodeNext",
    "noImplicitReturns": true,
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "baseUrl": "src",
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true
  },
  "compileOnSave": true,
  "include": ["src"]
}

二、配置WebStorm自动生成带.js的导入

光改编译配置还不够,要让IDE自动生成正确的导入,需调整WebStorm的设置:

  • 打开设置(快捷键Ctrl+Alt+S),进入Languages & Frameworks > TypeScript > Imports
  • 将Module style设置为ES modules
  • 勾选Add file extensions下的.js选项
  • 确保WebStorm使用项目本地的TypeScript版本(在Languages & Frameworks > TypeScript页面设置),这样IDE会完全遵循你的tsconfig规则

三、验证效果

修改完成后:

  • 手动编写不带.js扩展名的导入时,TypeScript会立刻报错,提示缺少扩展名
  • 在WebStorm中通过自动导入功能添加模块时,会自动带上.js扩展名

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 15:02:11