在Rails项目安装PhotoEditor SDK遇ForOfStatement类型错误求助
解决Rails项目中PhotoEditor SDK安装时的Babel ForOfStatement错误
问题详情
在Ruby on Rails项目中按照官方文档安装PhotoEditor SDK库后,DOM控制台出现如下编译错误:
Uncaught Error: Module build failed (from ./node_modules/babel-loader/lib/index.js): Error: /Users/robeen/dev/cocoon-immo/node_modules/photoeditorsdk/esm/chunk-2FC7YEBB.js: unknown Statement of type "ForOfStatement"
已完成所有必要peer依赖(React、React DOM、Styled Components等)的安装,开发环境信息:
- Node: v14.15.5
- Ruby: ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [arm64-darwin21]
- Rails: Rails 6.1.7.3
- NPM: 8.11.0
解决方案
1. 完善Babel对ES6+语法的支持
ForOfStatement属于ES6语法,当前Babel配置可能未启用对应转换插件。在项目根目录的.babelrc或babel.config.js中添加如下配置:
{ "presets": [ ["@babel/preset-env", { "targets": { "node": "14.15.5", "browsers": ["last 2 versions", "not dead"] } }], "@babel/preset-react" ], "plugins": ["@babel/plugin-transform-for-of"] }
2. 配置Webpacker转译node_modules中的PhotoEditor SDK
Rails 6的Webpacker默认不会转译node_modules内的包,需修改config/webpack/environment.js,让babel-loader处理PhotoEditor SDK的文件:
const { environment } = require('@rails/webpacker') const path = require('path') environment.loaders.get('babel').include.push( path.resolve(__dirname, '../../node_modules/photoeditorsdk') ) module.exports = environment
3. 更新Babel相关依赖版本
当前Node版本与Babel依赖可能存在兼容性问题,执行以下命令升级适配的依赖版本:
npm install @babel/core@^7.20.0 @babel/preset-env@^7.20.0 @babel/plugin-transform-for-of@^7.19.0 babel-loader@^9.1.0 --save-dev
4. 清理缓存并重新构建
执行以下命令清除缓存后重新编译项目:
rm -rf node_modules && npm install rails webpacker:clean rails webpacker:compile
内容的提问来源于stack exchange,提问作者user12178999
相关产品推荐
相关产品推荐

