關於@babel/polyfill -- 按需載入
什麼是@babel/polyfill
當babel幫我們編譯了es6語法之後,常常還會遇到了這樣的錯誤提示,比如我們在專案中運用了async/await。這時我們就需要@babel/polyfill為我們在全域性去注入這些ES6+的變數(或者屬性/方法)。
Babel includes a polyfill that includes a custom regenerator runtime
and core-js. This will emulate a full ES2015+ environment (no < Stage
4 proposals) and is intended to be used in an application rather than
a library/tool. (this polyfill is automatically loaded when using
babel-node). This means you can use new built-ins like Promise or
WeakMap, static methods like Array.from or Object.assign, instance
methods like Array.prototype.includes, and generator functions
(provided you use the regenerator plugin). The polyfill adds to the
global scope as well as native prototypes like String in order to do
this.
他會幫我們模擬一個es6+的環境,然後我們就可以愉快的使用es6+中的內建方法(Promise, WeakMap); 靜態方法(Array.from, Object.assign); 原型方法(如Array.prototype.includes, generator)。
使用
我們只需要安裝
npm install --save @babel/polyfill
然後在專案中引用進來就可以
require("@babel/polyfill"); or import "@babel/polyfill";
或者在webpack裡配置入口的時候加上去
main: ['@babel/polyfill', './src/main.js']
然而這樣會使我們的專案程式碼變得龐大
before:point_down:
after:point_down:
看著都嚇人,畢竟把es6+所有的東西都引入進來了,然而我們在專案中其實並沒有用到所有的語法,這時我們就可以按需引入@babel/polyfill。
按需引入
按官方文件可以用useBuiltIns的方法實現按需載入,只需在.babelrc中增加環境配置如下:point_down:
{ "presets": [["@babel/preset-env", { "useBuiltIns": "usage" }]], }
然而問題也出現了,webpack報了這樣的警告:point_down:
倒不是沒有安裝corejs, @babel/polyfill就已經包含了他,其實就是我們配置少了corejs, 修改如下:point_down:
{ "presets": [["@babel/preset-env", { "useBuiltIns": "usage", "corejs": 3 }]] }
這樣就ok了,專案中我只使用了generator, 所以只會把這部分的給引用進來。