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
相关产品推荐
相关产品推荐

