Babel’s translation process is also divided into three stages

  • Parsing the Parse
    • Parsing code to generate an abstract syntax tree (AST)
    • It is the process of lexical analysis and grammatical analysis
  • Transformation Transform
    • To perform a series of transformations on the AST, Babel takes the AST and traverse it with babel-traverse,
    • During this process, you can add, update, and remove
  • Generate the Generate
    • Convert the transformed AST into JS code,
    • The module used is babel-generator

2. How to write a Babel plugin?

var babel = require('babel-core');
var t = require('babel-types');

const visitor = {
    BinaryExpression(path) {
        const node = path.node;
        let result;
        
        // Check whether both sides of the expression are numbers
        if (t.isNumericLiteral(node.left) && t.isNumericLiteral(node.right)) {
            // Operate according to different operators
            switch (node.operator) {
                case "+":
                    result = node.left.value + node.right.value;
                    break
                case "-":
                    result = node.left.value - node.right.value;
                    break;
                case "*":
                    result = node.left.value * node.right.value;
                    break;
                case "/":
                    result = node.left.value / node.right.value;
                    break;
                case "* *":
                    let i = node.right.value;
                    while (--i) {
                        result = result || node.left.value;
                        result = result * node.left.value;
                    }
                    break;
                default:}}// If the above operation has any result
        if(result ! = =undefined) {
            // Replace the expression node with the number literalpath.replaceWith(t.numericLiteral(result)); }}};// So the Babel plug-in module requires you to expose a function that returns the visitor within the function
module.exports = function (babel) {
    return {
        visitor
    };
}

Copy the code
// Run the plug-in
const babel = require("babel-core");
const result = babel.transform("const result = 1 + 2;", {plugins: [require("./index")]});console.log(result.code); // const result = 3;

Copy the code