Webpack无法解析react-spring模块,遇可选链语法解析错误求方案
解决Webpack无法解析@react-spring/core中可选链操作符的问题
错误详情
ERROR in ./node_modules/@react-spring/core/dist/react-spring_core.legacy-esm.js
118:11 Module parse failed: Unexpected token (118:11) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
出错代码片段:ctrl.ref?.delete(ctrl); ref?.delete(ctrl);
问题原因
你的Webpack配置中,babel-loader规则设置了exclude: /node_modules/,直接排除了所有第三方模块的转译处理,但@react-spring/core的该文件使用了未转译的可选链(?.)语法,导致Webpack无法识别。
解决方案
方案一:调整Webpack配置,让babel-loader处理@react-spring模块
修改webpack.config.js中的babel-loader规则,修改排除逻辑,让@react-spring模块被babel-loader处理:
module: { rules: [ { test: /\.(js|jsx)$/, // 排除node_modules,但例外处理@react-spring下的文件 exclude: /node_modules(?!\/@react-spring)/, use: { loader: "babel-loader", // 这里无需重复配置presets,直接复用babel.config.json的全局配置即可 }, }, // 其余CSS/SCSS规则保持不变 ], }
方案二:升级@react-spring/core版本(可选)
部分旧版本的@react-spring/core未提供预转译的生产代码,升级到最新稳定版可以避免这个问题:
npm update @react-spring/core # 或使用yarn yarn upgrade @react-spring/core
验证修改
执行构建命令,确认错误消失:
npm run build # 或 yarn build
内容的提问来源于stack exchange,提问作者Khải Nguyễn
相关产品推荐
相关产品推荐

