Translation of ES6 from webpack-babael7

Time:2020-12-7

Now?JavaScriptCode is mainly usedES6Write, but not all browsers support itES6Grammar, therefore, needs some kind of transformation mechanism, that is, willES6+Grammar intoES5Grammar,babel7Can help us do it.

1. Introduction to Babel

babel-loaderIt’s awebpackThe loader is used to transfer theES6+Translate intoES5, to get startedbabel-loader, we need to install some dependencies tobabel7For example, there are some dependencies:

  • @babel/core
  • @babel/preset-env
  • @babel/plugin-transform-runtime
  • @babel/polyfill

The following is a detailed description of what these dependencies do:
@babel/core
This is the core package of Babel compiler library
@babel/preset-env
This package means that the latest translation rules will be automatically compiled when compiling. In addition to this package, there are also some rule packages, such asbabel-preset-es2015(willes6OfjavascriptCode conversion browser compatiblejavascriptCode),babel-preset-es2016(willes7OfjavascriptCode conversion browser compatiblejavascriptCode),babel-preset-es2017(willes8OfjavascriptCode conversion browser compatiblejavascriptCode) etc.
@babel/polyfill
Let’s move onbabel/polyfillIt’s something.babelThere is a very clear sentence on the official website,babelOnly responsible for compiling the syntax. When we write pointy functions,babelWill help you to compile it into ordinary functions, this is no problem, but, for example, we use it in the codepromisebabelThe packaged code is actually stillpromise, in the lower browser,promiseIt doesn’t support it, butbabelIt doesn’t help you with it, because it’s not something you need to do at the syntax compilation level. Do not convert newAPIIncluding, for exampleIterator、Generator、Set、Maps、Proxy、Reflect、Symbol、PromiseAnd other global objects.
Therefore, if we want to make the packaged code compatible with lower version browsers, we should also considerpromise,SetSuch a new grammar low version browser incompatibility problem, at this timebabel/polyfillIt’s on the stage. You just need to install it globallybabel/polyfill

npm install --save-dev @babel/polyfill

Then use it in your project, and your code won’t have the compatibility issues mentioned earlier.

import '@babel/polyfill'

But, directlybabel-polyfillThere will be some holes. The first one is to pollute the global environment. For example, the lower version browsers do notSet, butbabel-polyfillWill add a global variableSet。 Another problem is that it will cause code redundancy. For example, multiple modules are usedPromiseIn each module, there may be an independent pairPromiseDo compatibility code. So, usebabel-polyfillIt can solve the compatibility problem, but it’s not the best solution. So, it appearsbabel-plugin-transform-runtimeUsing this plug-in, you can solve the above problems.

@babel/plugin-transform-runtime
In order not to pollute global objects and built-in object prototypes, but also want to experience the pleasure of using fresh syntax. It can be used togetherbabel-runtimeandbabel-plugin-transform-runtime。 For example, the current operating environment does not supportpromiseCan be introduced bybabel-runtime/core-js/promiseTo getpromiseOr throughbabel-plugin-transform-runtimeAutomatically rewrite yourpromise。 One may wonder why there are tworuntimePlug ins, in fact, have historical reasons: at the beginning, onlybabel-runtimePlug in, but it’s inconvenient to use. It’s directly introduced into the codehelperFunction means that it cannot be shared, resulting in a lot of duplicate files in the final packagehelpercode. So,BabelDeveloped againbabel-plugin-transform-runtimeThis module will rewrite our code, such asPromiseRewritten as_Promise(just figuratively) and then introduce_Promise helperFunction. This avoids the pain of repeatedly packaging code and manually introducing modules.

in use@babel/plugin-transform-runtimeNeed to be installed before@babel/runtimeBecause the former relies on the latter.

Yesbabel-runtimeYou can use itbabel-polyfillYes, link https://babeljs.io/docs/en/babel-plugin-transform-runtime/ There are instructions

2. Configuring Babel in webpack

① Installation dependency

npm i @babel/core babel-loader @babel/preset-env @babel/plugin-transform-runtime @babel/polyfill @babel/runtime--save-dev

② Create a new file named. Babelrc in the root directory of the project to configure Babel:

{
  "presets": ["@babel/preset-env"],
  "plugins": ["@babel/plugin-transform-runtime"]
}

③ Webpack configuration loader

module: {
  rules: [
    {
      Test: / \. JS $/, // use regular to match JS files
      exclude: /node_ Modules /, // exclude dependent package folder
      use: {
        Loader: 'Babel loader' // use Babel loader
      }
    }
  ]
}

webpack.config.js Final configuration:

const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

module.exports = {
  Entry: '/ babel7 escaped ES6. JS',
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'bundle.js',
    publicPath: __dirname + '/build/'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  },
  plugins: [
    // the last plug in will be deleted, and then the webpack () will be rebuilt
  ]
}

④ In app.js Introduce @ Babel / Polyfill globally and write ES6 syntax, and execute NPM run build package

//Test whether the ES6 syntax is translated by Babel

import '@babel/polyfill'
const array = [1, 2, 3]
const isES6 = () => console.log(...array)

isES6()

const arr = [new Promise(() => {}), new Promise(() => {})]

arr.map(item => {
  console.log(item)
})

Translation of ES6 from webpack-babael7
The global introduction of @ Babel / Polyfill may import unnecessary Polyfill in the code, thus making the packing volume larger
Change. Babelrc to translate only what we use

/**
*Babel configuration file
*/
{
  "presets": [
    [
      "@babel/preset-env",
      {
        "Usebuiltins": "usage", // introduced on demand
        "corejs": "3.3.2"
      }
    ]
  ],
  "plugins": ["@babel/plugin-transform-runtime"]
}

At the same time, comment out the code of global introduction and package it again

//Global introduction
// import '@babel/polyfill'

Translation of ES6 from webpack-babael7
Reference articles:
https://zhuanlan.zhihu.com/p/35378233
https://juejin.im/post/5a96859a6fb9a063523e2591
https://www.jianshu.com/p/7bc7b0fadfc2
https://github.com/SunshowerC/blog/issues/4