Front-end – Experience the AST tree of JS

What is?

A tree representation of the abstract syntactic structure of source code

Experience website: esprima.org/demo/parse….

For example, the AST tree of var a = 1 (one of the expressions) is

{
  "type": "Program"."body": [{"type": "VariableDeclaration"."declarations": [{"type": "VariableDeclarator"."id": {
            "type": "Identifier"."name": "a"
          },
          "init": {
            "type": "Literal"."value": 1."raw": "1"}}]."kind": "var"}]."sourceType": "script"
}
Copy the code

Code experience

Var aa = 1; const result = 1

Js -> ast -> js

  1. getvar aa = 1The ast tree
  2. Modify the ast tree
  3. Generate js code from ast tree:const result = 1
const esprima = require("esprima"); // Function: Generate ast tree from ECMAScript(JS) code
const estraverse = require("estraverse"); // Traverses the AST tree
const escodegen = require("escodegen"); // Generate ECMAScript(JS) code according to the AST tree

let code = "var aa = 1";
let tree = esprima.parseScript(code); // Generate ast tree from ECMAScript(JS) code

// Walk through the AST syntax tree
estraverse.traverse(tree, {
  enter(node) {
    // console.log("enter", node);
    if (node.kind === 'var') { // Replace var with const
      node.kind = 'const'
    }
    if (node.type === 'VariableDeclarator') { // Change the variable name
      node.id.name = node.id.name === 'aa' ? 'result' : node.id.name
    }
  },
  leave(node) {
    // console.log("leave", node);}});// Generate ECMAScript(JS) code according to the AST tree
let compileTreeJS = escodegen.generate(tree);
console.log(compileTreeJS);
// output: const result = 1;
Copy the code

Widely used

  1. Browser, intelligent compiler code syntax check, code style check, code formatting, code highlighting, code error prompts, code completion and so on
    • For example, ESLint checks for code errors or styles to find potential errors
    • IDE error prompts, formatting, highlighting, autocomplete, and more
  2. Code obfuscation compression
    • UglifyJS etc.
  3. Optimization changes the code, changes the code structure to achieve the desired structure
    • babel
    • Code packaging tools webpack, rollup, and more
    • CommonJS, AMD, CMD, UMD, etc
    • TypeScript, JSX, etc. Convert to native Javascript
    • This idea is also applied in vue.js, for example, the first step in the process of converting the template (HTML) written in the code into the render function is to parse the HTML string to generate the AST