This is the sixth day of my participation in the More text Challenge. For details, see more text Challenge

preface

In the previous article, we have been able to import various resources through JS. There is still the issue of translating the ES6 + code into ES5 and adding a polyfill to address browser compatibility issues. Babel is designed to solve this problem.

babel

Since Babel is divided into multiple packages, beginners can often get confused. Here, I’ll explain what each commonly used Babel package does.

  1. Babel /core: will only convert ES6 + syntax to ES5 syntax, but will not convert new APIS like: Promise.
  2. @babel/preset-env: Smart preset, includes a set of plugins that control how to add polyfills (compatible with new apis), you can add polyfills as needed, without polluting the global environment and stereotypes.
  3. @babel/ plugin-transform-Runtime: Needs to work with @babel/ Runtime so that the secondary code is introduced as a separate module, reducing the size of the compiled code. (This part, the official document also does not explain clearly, just my personal opinion)
  4. Babel/CLI: provides a CLI command line tool for compiling files from the command line, suitable for installation into local projects (note: this article does not describe how to use this package).

Before some Babel 7.4+, there was an important plugin named @babel/ Polyfill, which has been deprecated, so let me remind you that it does not need to be used again, in case you are misled by some old blogs.

  1. @babel/polyfill: The polyfill, which includes the core-JS and ReGenerator Runtime modules, adds various new apis that es5 does not have. By default, it is not added on demand, so it becomes very large. This is a plug-in that the source code runs before, and needs to be installed with -S.

If these Babel packages are to be used on a WebPack project, they need to be used by babel-Loader.

The use of Babel

Install babel-Loader, @babel/core, and @babel/preset-env to convert ES6 + syntax to ES5 and add polyfill as needed

npm i -D babel-loader @babel/core @babel/preset-env
Copy the code

Configure the following code in WebPack. Note that you need to add exclude to prevent node_modules and bower_components from being converted. Package management downloads do not need to be converted.

webapck.config.js

module.exports = {
    ...
    module: {
     rules: [{...test: /\.m? js$/,
            exclude: /(node_modules|bower_components)/,
            use: {
              loader: 'babel-loader'.options: {
                presets: ['@babel/preset-env'}}}}Copy the code

If you need to add plug-ins, such as @babel/plugin-proposal-object-rest-spread, you can add the plugins attribute in options to introduce the corresponding plug-ins.

Note: This plug-in has been included in @babel/preset-env, no additional installation is required, this plug-in is used to handle the RESET parameter and spread extension operator of ES6

webpack.config.js

module.exports = {
    ...
    module: {
     rules: [{...test: /\.m? js$/,
            exclude: /(node_modules|bower_components)/,
            use: {
              loader: 'babel-loader'.options: {
                presets: ['@babel/preset-env'].plugins: ['@babel/plugin-proposal-object-rest-spread'}}}}Copy the code

Improved Babel translation speed

Set cacheDirectory to true in options to enable caching of the results of babel-Loader’s execution. Every subsequent webPack build will attempt to read the cache. The default cache directory is node_modules/.cache/babel-loader for the project. If node_modules is not found, it will be cached in the system’s default temporary folder.

webpack.config.js

module.exports = {
    ...
    module: {
     rules: [{...test: /\.m? js$/,
            exclude: /(node_modules|bower_components)/,
            use: {
              loader: 'babel-loader'.options: {
                presets: ['@babel/preset-env'].plugins: ['@babel/plugin-proposal-object-rest-spread'].cacheDirectory: true}}}]}}Copy the code

NPM run build is executed. Node_modules generates some cache files related to Babel translation

Reduce the volume of Babel compiled code

Babel uses secondary code (such as _extend) for public methods, which is added by default to every file that requires secondary code. You need to install @babel/ plugin-transform-Runtime and @babel/ Runtime to introduce the helper code as a separate module.

npm i -D @babel/plugin-transform-runtime @babel/runtime
Copy the code

Add @babel/ plugin-transform-Runtime to your plugins

webpack.config.js

{
    test: /\.m? js$/,
    exclude: /(node_modules|bower_components)/,
    use: {
      loader: 'babel-loader'.options: {
        presets: ['@babel/preset-env'].plugins: ['@babel/plugin-proposal-object-rest-spread'.'@babel/plugin-transform-runtime'].cacheDirectory: true,}}}Copy the code

The complete code

directory

webpack.config.js

const path = require('path')

const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

console.log('Environment variables:', process.env.NODE_ENV)

module.exports = {
  // entry: path.resolve(__dirname, '.. /src/js/index.js'),
  entry: {
    main: path.resolve(__dirname, '.. /src/js/index.js'),
    header: path.resolve(__dirname, '.. /src/js/header.js'),
    footer: path.resolve(__dirname, '.. /src/js/footer.js'),},output: {
    // filename: 'main.js',
    filename: 'js/[name].[fullhash].js'.path: path.resolve(__dirname, '.. /dist'),
    // assetModuleFilename: 'img/[hash][ext][query]' // Globally specify the output location and filename of the resource file
  },
  // devServer: {
  // port: 3000,
  // hot: true,
  // contentBase: '.. /dist'
  // },
  plugins: [
    // new HtmlWebpackPlugin({
    //   title: '首页'
    // }),
    // Configure multiple htmlWebPackPlugins for as many pages as possible
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '.. /src/html/index.html'),
      filename: 'index.html'.chunks: ['main'] // The module name corresponding to the entry file (entry configuration), which can be understood here as importing main.js
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '.. /src/html/header.html'),
      filename: 'header.html'.chunks: ['header']}),new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '.. /src/html/footer.html'),
      filename: 'footer.html'.chunks: ['footer']}),new CleanWebpackPlugin(),
    new MiniCssExtractPlugin({
      filename: 'css/[name].[fullhash].css'})].module: {
    rules: [{test: /\.css$/i,
        use: [
          //'style-loader', 'css-loader'
          MiniCssExtractPlugin.loader, 'css-loader'] {},test: /\.s[ac]ss$/i,
        use: [
          MiniCssExtractPlugin.loader, 'css-loader'.'sass-loader']},/ / {
      // test: /\.(jpe? g|png|svg|gif)/i,
      // type: 'asset/resource',
      // generator: {
      // filename: 'img/[hash][ext][query]
      / /}
      // },
      / / {
      // test: /\.(jpe? g|png|svg|gif)/i,
      // type: 'asset/inline',
      // },
      {
        test: /\.(jpe? g|png|svg|gif)/i,
        type: 'asset'.generator: {
          filename: 'img/[hash][ext][query]' // Locally specify the output location
        },
        parser: {
          dataUrlCondition: {
            maxSize: 8 * 1024 // Limit to 8KB}}}, {test: /\.txt/,
        type: 'asset/source'
      },
      {
        test: /\.m? js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader'.options: {
            presets: ['@babel/preset-env'].plugins: ['@babel/plugin-proposal-object-rest-spread'.'@babel/plugin-transform-runtime'].cacheDirectory: true}}}]},resolve: {
    alias: {
      The '@': path.resolve(__dirname, '.. /src'),
      // You can continue to add aliases}}}Copy the code

series

Using WebPack5 (0) : Concepts Using WebPack5 (1) : Starting Using WebPack5 (2) : Configuring Multiple environments Using WebPack5 (3) : Loading the CSS Using WebPack5 (4) : Load resource file Webpack5 use (5) : Babel translation JS code use (6) : optimization