One, foreword

Recently I came across @Babel/Polyfill which was officially scrapped in 2020. Then we used the same package in part of the project to see if there was any room for optimization.

I read all the articles and official documents. Some new articles were also found to have information lag, and some were found to have the configuration of old and new versions mixed. So I want to check myself, follow the official document configuration, bit by bit to remove the corresponding option configuration to test. In general, it can be divided into two sets of recommended configuration of development mode, business application development and class library development. There are also several important versions.

  • Babel6, babel7.4
  • core-js@2 core-js@3

This article is mainly for ^babel7.4 and core-js@3 configuration, the following configuration is practiced, can be directly used.

Two, configuration details

1. Business application project

Rely on

  • Development depends on
  • Production depend on
    • The core – js @ 3. Babel, the shim of the browser API, currently only deals with lexical environments, all of which are handled by Core-JS
    • Regenerator – the runtime. It is also a kind of gasket

The command

// The purest configuration in business development
yarn add -D @babel/core@7.16. 0 babel-loader@8.22. @babel/preset-env@7.164.

yarn add --save core-js@3 regenerator-runtime
Copy the code

Babel. Config. Js configuration

module.exports = {
  presets: [['@babel/preset-env',
      {
        useBuiltIns: 'usage'.// Import on demand
        modules: false.// Easy tree shaking
        corejs: {
          version: 3./ / use the core - js @ 3
          proposals: true,},debug: true./ / log
        targets: { // Target browser, same as browserslist
          chrome: '58'.ie: '11',},},],}Copy the code

Compare the configurations of earlier versions

Prior to Babel7.4, much of this was configured via @babel/preset-env + @babel/polyfill. Even some older projects directly introduce polyfill js. There are several problems with this

  • Volume is too large
  • Contaminate the global environment
  • Some apis are not supported. Examples include flat, flatMap, and [].includes

@babel/polyfillThe github repository is no longer recommended.

2. Class library development

Rely on

  • Development depends on
    • @ Babel/[email protected]. Babel core package, must install
    • [email protected]. Output JS transformation, webpack must be installed
    • @ Babel/[email protected]. Babel environment presets, business applications and class library development need to be installed
    • @ Babel/plugin – transform – runtime. It is mainly used with @babel/ Runtime to automatically import locally imported APIS. Another function is to avoid repeated helper function references and reduce volume.
  • Production depend on
    • @ Babel/runtime – corejs3. Avoid contaminating the whole world with polyfill. It contains regenerator-Runtime and a series of other Runtime modules

Babel. Config. Js configuration

module.exports = {
  presets: [['@babel/preset-env',
      {
        modules: false,}]].plugins: [['@babel/plugin-transform-runtime',
      {
        corejs: {
          version: 3.proposals: true,},useESModules: true,},],],}Copy the code

The important thing to note here is that it is configured below@babel/plugin-transform-runtimeAfter this plugin, do not configure the useBuiltIns option in the above default, it will report an error. For details, please refer to the author’s reply under this issue.Click here to jump

Wrong demonstration of some articles

3. Configuration practice

Because ie does not support many features, HERE I use IE11 for testing.

1. Test code

/** * test Promise API * @author waldon * @date 2021-11-26 */ export const promiseFn = function () {return Resolve ('1')} /** * test Map API * @author waldon * @date 2021-11-26 */ export const mapFn = function () {const map = new Map() map.set('1', Const flatFn = function () {return map} /** * export const flatFn = function () { return [[1], 2].flat()} /** * test Class * @author waldon * @date 2021-11-26 */ export Class ClassTest {static num = 1} /** * test async  await * @author waldon * @date 2021-11-26 */ export const asyncFn = async function () { const foo = await Promise.resolve('async') return foo }Copy the code

2. UseBuiltIns by default

An optional value

  • False. The default value. All gaskets will be introduced, resulting in excessive volume, not recommended.
  • Entry. Different core-js and Regenerator-Runtime/Runtime are introduced in the entry depending on the environment
    • These two modules need to be imported into the entry JS
      import 'core-js/stable'
      import 'regenerator-runtime/runtime'
      Copy the code
  • The usage. On demand. This on demand means that the API module is introduced only when the JS used by the js file is not supported by the browser.

3. Configure babel-Loader

module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
      },
    ],
},
Copy the code

4. The configuration takes effect

Console Log Output

You are advised to enable this function during configurationdebug: trueYou can view the differences between the output information of each configuration.

API testing in IE11

5. Some errors are resolved

“Syntax error” in Internet Explorer or other older browsers

This is because the browser does not support the arrow functionoutputAdd configuration to

Output: {environment: {arrowFunction: false, output: {environment: {arrowFunction: false,Copy the code

Do not support the Promise

  • Probably in babel.config.jspresetsDon’t take effect.
  • Check if option in babel-loader in webpack.config.js is also configured with presets causing the configuration in babel.config.js to be overwritten

Does not support a flat

  • Check that core-js@3 is correctly referenced, as the flat and includes apis are not supported in core-js@2.
  • Or check to see if @babel/ plugin-transform-Runtime is configured in plugins and useBuiltIns is configured in presets.

Four, reference

  • Babeljs. IO/docs/en/USA… Babel’s official website
  • Github.com/zloirock/co… Recommended by core-JS authors
  • Segmentfault.com/a/119000002… The renewal of the corejs3
  • www.zhouzh.tech/posts/7842f… A polyfill reflection on Babel

Five, the summary

Practice is the mother of wisdom. The front end of the knowledge update iteration is too fast, there are a lot of norms and information that may be applicable at the time, but will also be eliminated. Frame class things as far as possible to try their own wave, otherwise there will be a lot of hidden pits and bugs.