Webpack Encore+TypeScript项目引入react-navigation时import type加载报错求助
问题原因
react-navigation相关依赖内部使用了TypeScript的import type/typeof类型导入语法,但当前Webpack Encore的TypeScript配置未正确支持这类语法,导致loader无法处理对应文件。
解决方案
1. 升级TypeScript版本
确保TypeScript版本在4.5及以上(import type最低要求3.8+,更高版本能更好兼容第三方库语法):
yarn add typescript@latest --dev
2. 调整Webpack Encore配置
在webpack.config.js中,确保TypeScript loader关联tsconfig文件,并启用React预设(React项目必须配置):
Encore // ... 其他已有配置 .enableTypeScriptLoader(options => { options.transpileOnly = true; options.configFile = './tsconfig.json'; // 指定你的tsconfig路径 }) .enableReactPreset() ;
3. 更新tsconfig.json配置
修改tsconfig.json,添加/调整以下关键配置项:
{ "compilerOptions": { "target": "ES2020", "module": "ESNext", "moduleResolution": "node", "allowSyntheticDefaultImports": true, "esModuleInterop": true, "isolatedModules": true, // 适配transpileOnly模式,支持模块级语法处理 "jsx": "react-jsx", // React 17+推荐使用 "strict": true, "skipLibCheck": true // 跳过第三方库类型检查,避免依赖内部类型文件报错 }, "include": ["src/**/*"] }
4. 配置Babel支持TypeScript(若项目使用Babel)
安装@babel/preset-typescript并更新Babel配置:
yarn add @babel/preset-typescript --dev
在babel.config.js中添加预设:
module.exports = { presets: [ '@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript' ] };
5. 清理缓存并重新构建
yarn cache clean rm -rf node_modules dist yarn install yarn watch
内容的提问来源于stack exchange,提问作者Charrier Alexis
相关产品推荐
相关产品推荐

