使用Webpacker的Rails-React应用中Babel Loader无法加载TypeScript依赖
问题描述
在Rails后端+React前端的一体化应用中,使用webpacker gem编译React代码时,导入TypeScript库wagmi后本地运行报错:
chains.js:3 Uncaught Error: Module parse failed: Unexpected token (546:49) File was processed with these loaders: * ./node_modules/babel-loader/lib/index.js You may need an additional loader to handle the result of these loaders. | if (!enabled) return; | if (!watch && !onBlock) return; > const publicClient_ = webSocketPublicClient ?? publicClient; | const unwatch = publicClient_.watchBlockNumber({ | onBlockNumber: blockNumber => { at ./node_modules/wagmi/dist/index.js (chains.js:3:1) at __webpack_require__ (bootstrap:19:1) at ./app/javascript/components/App.jsx (index.scss:19:1) at __webpack_require__ (bootstrap:19:1) at ./app/javascript/packs/Index.jsx (SurveyContent.jsx:165:1) at __webpack_require__ (bootstrap:19:1) at bootstrap:83:1 at bootstrap:83:1
已尝试执行bundle exec rails webpacker:install:typescript和npm install @babel/preset-typescript,并配置了config/webpacker.yml和babel.config.js,启动命令为rails s --binding=127.0.0.1。
问题原因
- 报错中的
??是ES2020空值合并运算符,当前Babel配置未启用对该语法的转译支持。 - Wagmi库的发布包未完全转译至低版本ES语法,导致Webpack通过Babel处理时无法识别该语法。
- 仅安装
@babel/preset-typescript不足以处理ES新语法,还需确保@babel/preset-env正确配置以覆盖ES2020及以上的语法转译。
调试与解决方法
1. 检查并更新Babel配置
修改babel.config.js,确保包含@babel/preset-env并配置目标环境,同时添加必要的语法插件:
module.exports = function(api) { api.cache(true); const presets = [ '@babel/preset-react', '@babel/preset-typescript', [ '@babel/preset-env', { targets: { browsers: ['last 2 versions', 'not ie <= 11'], node: 'current' }, useBuiltIns: 'usage', corejs: 3 } ] ]; const plugins = [ '@babel/plugin-proposal-nullish-coalescing-operator', '@babel/plugin-proposal-optional-chaining' // 可选,处理?.语法 ]; return { presets, plugins }; };
安装缺失的依赖:
npm install @babel/preset-env @babel/plugin-proposal-nullish-coalescing-operator @babel/plugin-proposal-optional-chaining core-js@3
2. 配置Webpacker处理node_modules中的ES语法
默认Webpacker可能不会转译node_modules中的包,需修改Webpack配置,让Babel处理wagmi及其依赖:
在config/webpack/environment.js中添加:
const { environment } = require('@rails/webpacker'); const babelLoader = environment.loaders.get('babel'); // 让Babel转译wagmi及其相关依赖包 babelLoader.exclude = /node_modules\/(?!(wagmi|@wagmi|viem)\/)/; module.exports = environment;
3. 清理缓存并重启服务
执行以下命令清理Webpack和Rails缓存:
bundle exec rails webpacker:clean bundle exec rails tmp:clear
然后重启Rails服务器:
rails s --binding=127.0.0.1
4. 验证TypeScript配置
确保tsconfig.json存在于项目根目录,且配置合理:
{ "compilerOptions": { "target": "ES2020", "module": "ESNext", "lib": ["ES2020", "DOM"], "jsx": "react-jsx", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["app/javascript/**/*"] }
内容的提问来源于stack exchange,提问作者Greg E
相关产品推荐
相关产品推荐

