preface

When learning how to configure Babel, I have been confused about how to use @babel/polyfill, @babel/ Runtime and @babel/plugin-transform-runtime. Now I will sum up my understanding. If there are any mistakes, I hope the officer can correct me.

@babel/preset-env

Perform Syntax transforms, as well as polyfills, depending on the configured browser environment

{
  "presets": [["@babel/preset-env"]]}Copy the code

The source code The transformed code(Contains a large number of auxiliary functions)

This is just for class, async/await syntax, but promises are not extended, but the @babel/preset-env parameter can be configured;

useBuiltIns

Configure @babel/preset-env how to handle polyfill

{
  "presets": [["@babel/preset-env", {
      "useBuiltIns": "usage"}}]]Copy the code

Regenerated code

Add the above code,

  • Introduced regenerator-Runtime and core-js dependencies (@babel/polyfill)
  • Extend the package to Promise

@babel/polyfill

🚨 As of Babel 7.4.0, this package has been deprecated in favor of directly including core-js/stable (to polyfill ECMAScript features) and Regenerator-runtime /runtime (needed to use transpiled generator functions) After 7.4.0 this package is deprecated, Regenerator-runtime and core-js packages need to be installed directly

For this, @babel/polyfill is used in an environment with Babel < 7.4.0

@ Babel/runtime and @ Babel/plugin – transform – runtime

@babel/runtime

  • Application environment: production environment
  • Installation mode: YARN add@babel/Runtime

@babel/plugin-transform-runtime

  • Usage environment: Development environment
  • Installation mode: YARN add — dev@babel /plugin-transform-runtime

{
  "presets": [["@babel/preset-env", {
      "useBuiltIns": false."corejs": false}]],"plugins": [["@babel/plugin-transform-runtime"] // corejs: false]}}Copy the code

The @babel/polyfill extension was removed and the @babel/ Runtime extension was added, but Promise was still not extended. That’s because we didn’t configure corejs for @babel/ plugin-transform-Runtime, which defaults to false

  • corejs: false.2.3 or { version: 2 | 3, proposals: boolean }, defaults to false

Corejs: 2: supports only global variables and static properties such as Promise, array. from corejs: 3: contains not only corejs2 features, but also instance properties (prototype chain) : [].includes() Install dependent packages as required

corejs option Install command
false npm install --save @babel/runtime
2 npm install --save @babel/runtime-corejs2
3 npm install --save @babel/runtime-corejs3

Babel configuration file

An extension to Promise has been added

conclusion

  1. For Babel < 7.4.0:, use @babel/polyfill in conjunction with useBuiltIns and Corejs of @babel/preset-env
  2. For Babel >= 7.4.0: Turn off @babel/preset-envuseBuiltIns: false 和 corejs: false , using @babel/runtime and @babel/plugin-transform-runtime