Bable source main process analysis

A simple case

Simple case open way into the mysterious Bable ast source analysis tool AST Explorer

// To parse source code into ast
const parser = require('@babel/parser')
// To manipulate the AST
const t = require('@babel/types')
// To traverse the AST
const traverse = require('@babel/traverse').default
// It is used to produce the processed code
const generate = require("@babel/generator").default


let code = 'var ab = 123; '

const ast = parser.parse(code);


traverse(ast, {
 Identifier(path) {
        path.node.name = path.node.name.split(' ').reverse().join(' ');
      },
      VariableDeclaration(path){
      	path.node.kind="let";
      },
      NumericLiteral(path){
        path.replaceWith(t.arrayExpression([t.stringLiteral("1"),t.booleanLiteral(false),t.nullLiteral(),t.objectExpression([t.objectProperty(t.stringLiteral("name"), t.stringLiteral("123")))))}})const output = generate(ast, {}, code)
Copy the code

Command processing

"scripts": {
        "build": "babel src --copy-files --out-dir lib"
 },
Copy the code

The process is as follows:

  • NPM finds the Babel command from node_modules’.bin directory, and NPM extracts it from the bin entry specified in the package.json file in babel-cli

  • Run lib/ Babel /index.js under Babel -cli

  • Processing input commands

This stage mainly normalizes the user’s parameter commands

Before compiling

  • Determine the compile target

Compile target: file or folder

  • Determine the relative path of the compiled file

  • Load the bable file configuration

  • Get compiled source code

Compilation of

  • Specification file object file, compiled to AST using able-paser, specification configuration object and merge

  • Use able-travers to traverse the file AST object and use able-type to process the source code according to configuration items

  • Generate the post-processing code using able-generate

Ps: code all in accordance with node-moudel source code analysis