JavaScript

超轻量级php框架startmvc

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

更新时间:2020-08-25 19:36 作者:startmvc
最近工作比较忙,有一段时间没有写前端玩了。今天试着搭一个项目,发现各种坑,以前用

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

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