Babel Starter -1 Write your own plugin

Introduction to the

Babel, often referred to as “Babel”, is a language-conversion plug-in that converts features not supported by browsers into features supported by lower versions. Learning about Babel will help you understand JS. The goal of this article is to write a Babel plug-in with minimal context.

AST

Abstract Syntax Tree === AST definition file: github.com/babel/babyl… Astexplorer.net/ can convert JS code to AST tree

The basic flow of Babel

Parsing: Parsing code into AST

Transform: Process the code to generate a new AST tree

Production: Convert the AST tree to new code

The process by which Babel processes code

1 Converts to ast

const babylon = require("babylon"); const code = `function add(a) { return a + 1; } `; const ast = babylon.parse(code); console.log('ast',ast)Copy the code

The above code can be converted to an AST

2 let’s deal with it

const babylon = require("babylon"); const traverse = require("babel-traverse"); const code = `function add(a) { return a + 1; } `; const ast = babylon.parse(code); const res = traverse.default(ast, { enter(path) { if (path.node.type === "Identifier" && path.node.name === "a") { path.node.name = "b"; }}}); console.log('ast',ast)Copy the code

The above code outputs variable A as b

3 Output code

const babylon = require("babylon");
const traverse = require("babel-traverse");
const generate = require("babel-generator");
const code = `function add(a) {  return a + 1;}`;
const ast = babylon.parse(code);
const res = traverse.default(ast, {
  enter(path) {
    if (path.node.type === "Identifier" && path.node.name === "a") {
      path.node.name = "b";
    }
  },
});

console.log("ast", ast);
const newcode = generate.default(ast, {}, code);
console.log("newcode", newcode);
// newcode {
//  code: 'function add(b) {\n  return b + 1;\n}',
//  map: null,
//  rawMappings: null
// }

Copy the code

Output the transformed AST tree as code results.

A simple plug-in

Set up the plugin

// plugin.js module.exports = function({ types: babelTypes }) { return { name: "name-transfer-plugin-example", visitor: { Identifier(path, state) { if (path.node.name === 'tttt') { path.node.name = 'aaaa'; }}}}; };Copy the code

The purpose of this plug-in is to convert the variable TTTT to AAAA.

Configure the plug-in

In the.babelrc file

{
  "plugins": [
    "@babel/plugin-transform-arrow-functions",
    [
      "./plugins/helloworld",
      {
        "alipay": "mababa",
        "live": "booking"
      }
    ]
  ]
}

Copy the code

Compiled using the Babel

Insert a run script inside scripts to edit Babel, and after compiling you can see the result.

  "scripts": {
    "build": "babel src -d lib",
  },
Copy the code

The results are as follows:

Let TTTT = 'test plug-in '; // ---- let aaaa = 'test plug-in ';Copy the code

Reference manual

  1. Github.com/jamiebuilds…
  2. ECMA specification www.ecma-international.org/ecma-262/5….
  3. IO /docs/en/bab…