學習 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倉庫 里找
最終文件
.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原創 , 采用《署名-非商業性使用-禁止演繹 4.0 國際》許可協議
轉自:https://segmentfault.com/a/1190000016458913 作者:Shurlormes