什么是@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, 所以只会把这部分的给引用进来。
发表回复