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

package.json设为type="module"时TS2604错误的解决方法

问题描述

编译TypeScript代码时触发TS Error 2604,仅在package.json保留"type": "module"时出现;改为"commonjs"或删除该字段可正常编译,但因业务需求必须保留"type": "module",需解决该错误。

相关代码与配置如下:

TypeScript组件代码

import React from "react";
import Tree from "rc-tree";
export function S() {
    return <Tree>
    </Tree>
}

package.json配置

{
  "type": "module",
  "dependencies": {
    "rc-tree": "^5.7.3",
    "react": "^18.2.0"
  },
  "devDependencies": {
    "@types/react": "^18.2.6"
  }
}

tsconfig.json配置

{
    "compilerOptions": {
        "outDir": "./build",
        "target": "es2020",
        "module": "es2020",
        "lib": ["es2020","dom", "DOM.Iterable"] ,
        "esModuleInterop": true,
        "jsx": "react",
        "moduleResolution": "node16",
        "strict": true,
        "sourceMap": true,
        "resolveJsonModule": true,
        "composite":true
    },
    "ts-node": {
        "compilerOptions": {
            "module": "CommonJS"
        }
    },
    "exclude": ["node_modules","webpack.config","build"],
    "include": ["**/*.ts*"]
}
解决方案

TS Error 2604源于ES模块与CommonJS模块解析时的类型兼容问题,保留"type": "module"的前提下,可通过以下步骤修复:

  • 调整模块解析策略
    修改tsconfig.json中compilerOptions的moduleResolution为bundler,该模式适配现代打包工具的模块处理逻辑,能更好兼容ES模块与第三方CommonJS依赖:

    "compilerOptions": {
        // 保留原有其他配置
        "moduleResolution": "bundler"
    }
    
  • 升级依赖版本
    尝试升级rc-tree至最新版本,后续版本可能已修复ES模块下的类型定义问题:

    npm install rc-tree@latest
    
  • 优化JSX编译配置
    若使用React 18+,将jsx配置改为react-jsx,该模式自动引入React运行时,更符合ES模块规范:

    "compilerOptions": {
        // 保留原有其他配置
        "jsx": "react-jsx"
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 01:02:16