温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

详解babel升级到7.X采坑总结

发布时间:2020-10-23 23:31:03 来源:脚本之家 阅读:199 作者:Shurlormes 栏目:web开发

最近工作比较忙,有一段时间没有写前端玩了。今天试着搭一个项目,发现各种坑,以前用起来非常好的配置文件各种报错。排查后发现原来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提交日志上看,作者已经支持了最新的babel。在之后的测试中,发现mobx的功能也能正常使用。

另外,stage-*已弃用

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仓库 里找

最终文件

.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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI