关于@babel/polyfill — 按需加载

59次阅读

共计 1368 个字符,预计需要花费 4 分钟才能阅读完成。

什么是 @babel/polyfill

当 babel 帮我们编译了 es6 语法之后,常常还会遇到了这样的错误提示,比如我们在项目中运用了 async/await。这时我们就需要 @babel/polyfill 为我们在全局去注入这些 ES6+ 的变量(或者属性 / 方法)。
Babel includes a polyfill that includes a custom regenerator runtimeand core-js. This will emulate a full ES2015+ environment (no < Stage4 proposals) and is intended to be used in an application rather thana library/tool. (this polyfill is automatically loaded when usingbabel-node). This means you can use new built-ins like Promise orWeakMap, static methods like Array.from or Object.assign, instancemethods like Array.prototype.includes, and generator functions(provided you use the regenerator plugin). The polyfill adds to theglobal scope as well as native prototypes like String in order to dothis.
他会帮我们模拟一个 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????

after????

看着都吓人,毕竟把 es6+ 所有的东西都引入进来了,然而我们在项目中其实并没有用到所有的语法,这时我们就可以按需引入 @babel/polyfill。
按需引入
按官方文档可以用 useBuiltIns 的方法实现按需加载,只需在.babelrc 中增加环境配置如下????
{
“presets”: [[“@babel/preset-env”, {
“useBuiltIns”: “usage”
}]],
}
然而问题也出现了,webpack 报了这样的警告????

倒不是没有安装 corejs, @babel/polyfill 就已经包含了他,其实就是我们配置少了 corejs,修改如下????
{
“presets”: [[“@babel/preset-env”, {
“useBuiltIns”: “usage”,
“corejs”: 3
}]]
}

这样就 ok 了,项目中我只使用了 generator,所以只会把这部分的给引用进来。

正文完
 0