Note: when we write ES6 code, not all browsers can be compatible, this time we can use Babel to convert to ES5 syntax

  • 1. Install

npm install --save-dev babel-loader @babel/core

  • 2. The configuration

Webpack. Config. Js

. module.exports = { ... module: { rules: [{ test: /\.m?js$/, exclude: /node_modules/, use: { loader: "babel-loader", options: { presets: ['@babel/preset-env'] } } }, ... ] },... }Copy the code
  • 3. The instructions

The above actions are just a bridge between Babel and JS code. If you can convert ES6 to ES5 code, you need to do the following

  • 4. Continue the installation

npm install @babel/preset-env --save-dev

  • 5. Addsrc/index.jscode
const arr = [
    new Promise(() => {}),
    new Promise(() => {})
];

arr.map(item => {
    console.log(item)
})
Copy the code
  • 6. Run the package operation

npm run build

  • 7. Package the results

Note: At this point, the ES6 syntax has been converted to ES5, but some browsers still cannot recognize the Promise map… At this point we need to move on.

  • 8. Use the polyfill

A. Install NPM install –save @babel/polyfill

B. Use the following code at the top of the business code SRC /index.js

import "@babel/polyfill";
Copy the code

Packaging is ok, but there is a problem, the package after packaging is too large, affecting the performance

C. The solution is somewhat similar to loading on demand, set up in webpack.config.js

. module.exports = { ... module: { rules: [{ test: /\.m?js$/, exclude: /node_modules/, use: { loader: "babel-loader", options: { presets: [['@babel/preset-env', { useBuiltIns: 'usage' }]] } } } ... ] },... }Copy the code
  • 9. Polyfill can be configured to select the corresponding browser development version to automatically determine whether they are converted to ES5 recognized.
. module.exports = { ... module: { rules: [{ test: /\.m?js$/, exclude: /node_modules/, use: { loader: "babel-loader", options: { presets: [['@babel/preset-env', { targets: { chrome: "67", }, useBuiltIns: 'usage' }]] } } } ... ] },... }Copy the code

Note: Because chrome supports a version larger than chrome, chrome can recognize the promise map notation, so it will not escape, reducing the size of the compressed code and improving performance.