当babel帮咱们编译了es6语法以后,经常还会遇到了这样的错误提示,好比咱们在项目中运用了async/await。这时咱们就须要@babel/polyfill为咱们在全局去注入这些ES6+的变量(或者属性/方法)。node
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)。webpack
咱们只须要安装
npm install --save @babel/polyfilles6
而后在项目中引用进来就能够
require("@babel/polyfill"); or import "@babel/polyfill";
或者在webpack里配置入口的时候加上去
main: ['@babel/polyfill', './src/main.js']web
然而这样会使咱们的项目代码变得庞大
before👇npm
after👇babel
看着都吓人,毕竟把es6+全部的东西都引入进来了,然而咱们在项目中其实并无用到全部的语法,这时咱们就能够按需引入@babel/polyfill。app
按官方文档能够用useBuiltIns的方法实现按需加载,只需在.babelrc中增长环境配置以下👇async
{ "presets": [["@babel/preset-env", { "useBuiltIns": "usage" }]], }
然而问题也出现了,webpack报了这样的警告👇ide
倒不是没有安装corejs, @babel/polyfill就已经包含了他,其实就是咱们配置少了corejs, 修改以下👇ui
{ "presets": [["@babel/preset-env", { "useBuiltIns": "usage", "corejs": 3 }]] }
这样就ok了,项目中我只使用了generator, 因此只会把这部分的给引用进来。