babel 版本原因运行报错,解决办法

学习 babel 时,遇到的问题,使用旧版本 babel 命名规则安装后运行报错,初步查找到原因是因为 babel 各个preset和plugin新旧不同版本之间存在兼容问题,提示使用 npx babel-upgrade 可以自动升级,但是我升级失败了,提示解析错误,后来看到了这篇文章,问题得以解决。现在被我原封不动的给扒了过来当笔记(复制,主要还是懒  [手动狗头])

babel 升级到7.X采坑总结

最近工作比较忙,有一段时间没有写前端玩了。今天试着搭一个项目,发现各种坑,以前用起来非常好的配置文件各种报错。排查后发现原来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仓库 里找

品牌vi设计公司http://www.maiqicn.com 办公资源网站大全https://www.wode007.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)

原文地址:https://www.cnblogs.com/xiaonian8/p/13690910.html