关于@babel/polyfill -- 按需加载

什么是@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

相关推荐