学习 babel 时,遇到的问题,使用旧版本 babel 命名规则安装后运行报错,初步查找到原因是因为 babel 各个preset和plugin新旧不同版本之间存在兼容问题,提示使用 npx babel-upgrade 可以自动升级,但是我升级失败了,提示解析错误,后来看到了这篇文章,问题得以解决。现在被我原封不动的给扒了过来当笔记(复制,主要还是懒 [手动狗头])
最近工作比较忙,有一段时间没有写前端玩了。今天试着搭一个项目,发现各种坑,以前用起来非常好的配置文件各种报错。排查后发现原来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
。在之后的测试中,发现mobx
的功能也能正常使用。
另外,
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
文件
具体的包名可以在 里找
.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
本作品系作者:shurlormes原创 ,
转自: 作者:shurlormes
如对本文有疑问, 点击进行留言回复!!
vue源码实战render.js与$nextTick的异步调用
同事牛逼啊,写了个隐藏 bug,我排查了 3 天才解决问题!
【JavaScript笔记(一)】万丈高楼平地起 - 基本概念篇
网友评论