[Use babel to handle ES6 syntax]

Using babel to handle ES6 syntax

Index. Write some ES6 syntax in the JS file

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

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


Package using the npx webpack command (webpack-dev-server is not used here because the packaged files are placed directly in memory, making it inconvenient for us to view the packaged files)

You can see the main generated by packaging. The last part of JS is that we are in index. Code for ES6 written in js.
However, this code will fail in the console in some browsers, such as IE browsers, which do not support ES6 syntax. So we want to package the ES6 code and convert it to ES5 code. So all browsers will be fine, let's use babel
Go to the babel website, click on the settings, choose the scene you use, here we choose webpack

1. Select a configuration scenario

2. Install related files


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

Here we need to install two files, babel-loader, to package ES6 code. babel-core is the core library of babel, which recognizes the contents of js code, converts it into an AST abstract grammar tree, and compiles it into a new grammar.

3. Configure Packaging Rules


Then add this rule to the webpack configuration file

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const webpack = require('webpack')

module.exports = {
    mode: "development",
    devtool: 'eval-cheap-module-source-map',
    // production
    // devtool: 'cheap-module-source-map',
    entry: {
        main: './src/index.js'
    },
    devServer: {
        contentBase: './dist',
        open: true,
        port: 8080,
        hot: true,
        // hotOnly: Do not let the browser refresh even if the hot feature does not work
        hotOnly: true
    },
    output: {
        publicPath: '/',
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist'),
    },
    module: {
        rules: [
            {
                test: /\.m?js$/,
                // exclude If your js file is in node_ babel-loader is not used in modules
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader",
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            },
            {
                test: /\.jpeg$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        name: '[name]_[hash].[ext]',
                        outputPath: 'images/',
                        limit: 10240
                    }
                }
            },
            {
                test: /\.s[ac]ss$/i,
                use: [
                    "style-loader",
                    {
                        loader: "css-loader",
                        options: {
                            importLoaders: 2
                        }
                    },
                    "postcss-loader",
                    "sass-loader"
                ]
            },
            {
                test: /\.(eot|ttf|svg|woff|woff2)$/,
                use: {
                    loader: 'file-loader',
                }
            },
            {
                test: /\.css$/,
                use: [
                    "style-loader",
                    "css-loader",
                    "postcss-loader",
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'src/index.html'
        }),
        new CleanWebpackPlugin(['dist']),
        new webpack.HotModuleReplacementPlugin()
    ]
}

4. Add translation module, add configuration file


Step 4 requires installation of babel/preset-env

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

When using babel-loader to process js files, it is actually a bridge between webpack and babel, but babel-loader does not convert the ES6 syntax in js into ES5 syntax, and it also needs to be translated with the babel/preset-env module. This module contains all translation rules for ES6 to ES5

Execute the npx webpack command again to package, and you can see that our code has been converted to ES5 code
Const --> var, () => --> function () {} and so on, but this is only part of the translation, and the syntax of some arrays is not supported on lower browsers. babel-polyfill is very large because it also helps us to add variables and functions to our lower browsers.


Install babel-polyfill and introduce babel-polyfill before all code runs

npm install --save @babel/polyfill
import "@babel/polyfill";

Compare two packages, because the introduction of babel-polyfill increases the size a lot

In theory, we only need babel-polyfill to implement our index. The Promise,map, and other methods in the JS file do not actually require all translation to implement ES6 syntax. Depending on the syntax for implementing ES6 from your business code, configure it as follows

{
                test: /\.m?js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader",
                    options: {
                        presets: [
                            ['@babel/preset-env',
                                {
                                    useBuiltIns: 'usage'
                                }
                            ]
                        ]
                    }
                }
            },

Executing npx webpack, you can see that the volume is much smaller than 167KB, so we can execute ES6 code normally in low version browsers, and the package volume is also reduced

Keywords: Javascript Front-end Webpack

Added by susi on Thu, 03 Feb 2022 19:16:52 +0200