企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持知识库和私有化部署方案 广告
# [babel 升级到7.X采坑总结](https://segmentfault.com/a/1190000016458913) [](https://segmentfault.com/a/1190000016458913) * [babel](https://segmentfault.com/t/babel/blogs) 最近工作比较忙,有一段时间没有写前端玩了。今天试着搭一个项目,发现各种坑,以前用起来非常好的配置文件各种报错。排查后发现原来`babel`升级了一个大版本,已经到`7.X`了,这里我总结一下升级过程中踩到的坑。 * * * ~~~ Error: Cannot find module '@babel/core' babel-loader@8 requires Babel 7.x (the package '@babel/core'). If you'd like to use Babel 6.x ('babel-core'), you should install 'babel-loader@7'. at Function.Module._resolveFilename (module.js:547:15) at Function.Module._load (module.js:474:25) at Module.require (module.js:596:17) at require (internal/module.js:11:18) .... ~~~ 没找到`@babel/core`,需要把`babel-core`卸载掉,从新安装`@babel/core` `npm un babel-core` `npm i -D @babel/core` * * * ~~~ ERROR in ./src/index.jsx Module build failed (from ./node_modules/babel-loader/lib/index.js): Error: Plugin/Preset files are not allowed to export objects, only functions. ... ~~~ 将`babel-preset-*`卸载,重新安装`@babel/preset-*`,并且修改`.babelrc`中的`presets` 比如我的 ~~~ npm: - babel-preset-env + @babel/preset-env - babel-preset-react + @babel/preset-react - babel-preset-stage-0 .babelrc: - "presets": ["react", "env", "stage-0", "mobx"] + "presets": ["@babel/preset-react", "@babel/preset-env", "mobx"] ~~~ 除了上述的`preset`,我还用了`babel-preset-mobx` 但是没找到`@babel/preset-mobx`,从[babel-preset-mobx git提交日志](https://github.com/zwhitchcox/babel-preset-mobx/commits/master)上看,作者已经支持了最新的`babel`。在之后的测试中,发现`mobx`的功能也能正常使用。 另外,[stage-\*已弃用](https://babeljs.io/blog/2018/07/27/removing-babels-stage-presets) * * * ~~~ ERROR in ./src/index.jsx Module build failed (from ./node_modules/babel-loader/lib/index.js): TypeError: this.setDynamic is not a function at PluginPass.pre ... ~~~ 这次是插件了,一样把`babel-plugin-*`卸载,重新安装`@babel/plugin-*` 然后修改`.babelrc`文件 具体的包名可以在[npm仓库](https://www.npmjs.com/)里找 ### 最终文件 `.babelrc:` ~~~ { "presets": ["@babel/preset-env", "@babel/preset-react", "mobx"], "plugins": [ "@babel/plugin-proposal-object-rest-spread", "@babel/plugin-transform-runtime" ] } ~~~ `package.json:` ~~~ "devDependencies": { "@babel/core": "^7.1.0", "@babel/plugin-proposal-object-rest-spread": "^7.0.0", "@babel/plugin-transform-runtime": "^7.1.0", "@babel/preset-env": "^7.1.0", "@babel/preset-react": "^7.0.0", "babel-loader": "^8.0.2" "babel-preset-mobx": "^2.0.0", ... }, "dependencies": { "@babel/runtime": "^7.0.0", ... } ~~~ ### 总结 这次升级,功能上有什么变化我就不在这里写了,大家可以自行搜索 总的来说,`babel`舍弃了以前的`babel-*-*`的命名方式,改成了`@babel/*-*` 修改依赖和`.babelrc`文件后就能正常启动项目了。 `webpack`不用修改(除非你是`webpack 3.X`升`webpack 4.X`) 上面的只是我遇到的问题,如果还有其他问题,可以参考资料[升级指南 Upgrade to Babel 7](https://babeljs.io/docs/en/v7-migration)