Learn the introduction and basic use of webpack: babel

Ask yourself more why every day. You always have unimaginable gains. A rookie Xiaobai's growth path (copyer)


Why do you need babel

There are many new grammars in the front end, such as ES6, TS, JSX, etc. they all need babel transformation

Therefore, learning Babel is very important for us to understand the transformation of code from writing to online

What is babel

  • Babel is a tool chain, which is mainly used to convert ES6 code into backward compatible JavaScript in old browsers or environments

  • Including: syntax conversion, source code conversion, etc

Babel's imperative use

babel itself can be used as an independent tool without using it with webpack

If you want to use the command line babel, you need to install the following libraries:

  • @Babel / core: the core code of Babel, which must be installed
  • @babel/cli: you can use babel on the command line

Installation:

npm install @babel/cli @babel/core -D

Use babel to process our source code:

  • src: directory of source files
  • – out dir: Specifies the folder dist to output
  • – out file: Specifies the file name of the output
npx babel src --out-file dist

Under the directory folder, create a new demo js

//demo.js
const message = 'james';

[1,2,3].map(n => n + 1);

Execute command

npx babel demo.js --out-file dist.js

Input results:

const message = 'james';
[1, 2, 3].map(n => n + 1);

It can be found that the conversion from ES6 code to ES5 code was not successful.

Why?

Because babel also needs plug-in support


Use of plug-ins

Plug in for arrow function

install

npm install @babel/plugin-transform-arrow-functions -D

Run command

npx babel demo.js --out-file dist.js --plugins=@babel/plugin-transform-arrow-functions 

You can successfully convert the arrow function into ES5 code.

Plug ins for block level scopes

Installation:

npm install @babel/plugin-transform-block-scoping -D

Run command

npx babel demo.js --out-file dist.js --plugins=@babel/plugin-transform-arrow-functions,@babel/plugin-transform-block-scoping

You can successfully turn const into var

However, there are too many syntax in ES6, so many plug-ins need to be installed, and the splicing of running instructions is also very long. What should we do?


preset of babel

There are many ES6 plug-ins built into preset, so you don't need to install and use them one by one. Just install preset directly

install

npm install @babel/preset-env -D

Run command

npx babel demo.js --out-file dist.js --presets=@babel/preset-env

effect

//Strict mode is also turned on
"use strict";

var message = 'james';
[1, 2, 3].map(function (n) {
  return n + 1;
});

In this way, most of the ES6 code can be converted into ES5 code


Underlying principle of babel

We can think of babel as a compiler

The function of babel compiler is to convert our source code into another source code that can be directly recognized by the browser

Compilation process of babel:

  • Parsing phase
  • Transformation phase
  • Code Generation

Implementation principle of babel compiler: (refer to the diagram of coderwhy teacher)

The detailed version is:

Simple explanation of specific steps:

  1. Original source code const name = "why"
  2. Lexical analysis is to cut sentences to form separate strings
  3. token array, put the generated string into the array ['const', 'name', '=', 'why']
  4. Syntax analysis, find out keywords, const
  5. Generate AST tree
  6. Traverse AST tree
  7. Access each node of the AST
  8. If it is a keyword, find the corresponding plug-in (convert const into var of ES5)
  9. Generate a new AST tree
  10. Generate the source code recognized by the converted browser

babel-loader

Generally speaking, babel is used in construction tools, such as webpack. Then you need the support of babel loader

install

npm install babel-loader -D

//If @ babel/core is not installed, it also needs to be installed. This is the core code of babel

use:

As above, when using babel, you also need plug-ins.

// webpack.config.js

module.exports = {
    //Setting mode
    mode: 'development',
    //Set source map and establish js mapping file to facilitate debugging code and errors
    devtool: 'source-map',
    //Entry file (address can be modified)
    entry: './src/index.js',
    //Packaged export file
    output: {
        //Packaged path
        path: path.resolve(__dirname, './build'),
        //Packaged file name
        filename: 'build.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: [
                    {
                        loader: 'babel-loader',
                        options: {
                            //plug-in unit
                            plugins: [
                                "@babel/plugin-transform-block-scoping",
                                "@babel/plugin-transform-arrow-functions"
                            ]
                            //Preset
                            presets: [   
                                "@babel/preset-env"   //Writing method 1: the form of string
                            
                            	//Writing method 2: the form of array
                            	["@babel/preset-env", { //Configuration of previous plug-ins}]
                                
                            ]
                        }
                    }
                ]
            }
        ]
    }
}

Of course, it can also be extracted separately

Configuration file for babel

Two forms

  • pbabel.config.json (or. js,. cjs,. mjs) files;

  • babelrc.json (or. Babelrc,. js,. cjs,. mjs) files

The writing is the same as above

//babel.config.js

module.exports = {
    presets: [
        "@babel/preset-env"
    ]
}
//webpack.config.js

module.exports = {
    //Setting mode
    mode: 'development',
    //Set source map and establish js mapping file to facilitate debugging code and errors
    devtool: 'source-map',
    //Entry file (address can be modified)
    entry: './src/index.js',
    //Packaged export file
    output: {
        //Packaged path
        path: path.resolve(__dirname, './build'),
        //Packaged file name
        filename: 'build.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: [
                    {
                        loader: 'babel-loader'
                    }
                ]
            }
        ]
    }
}

Keywords: Webpack

Added by franck on Wed, 05 Jan 2022 09:56:50 +0200