AST

Babel

Babel 是一个 JavaScript 编译器

Babel 是一个工具链,主要用于将采用 ECMAScript 2015+ 语法编写的代码转换为向后兼容的 JavaScript 语法,以便能够运行在当前和旧版本的浏览器或其他环境中。

官方文档:https://babeljs.io/docs/en/

中文文档:https://www.babeljs.cn/docs/

安装Babel

npm install @babel/parser @babel/core @babel/generator @babel/types

AST

AST,抽象语法树(abstract syntax code,AST)是源代码语法结构的一种的多叉树抽象表示。

在线解析

解析网站:https://astexplorer.net/

解析器设置为@babel/parser

AST使用

给定一段JS,利用AST修改 a 的值为How old are you??

var a ; a = "hi ast,How are you?"

node下运行得到结果

const {parse} = require('@babel/parser')
const generator = require('@babel/generator').default

const ast_code = parse('var a ; a = "hi ast,How are you?"')
console.log(ast_code)

ast_code.program.body[1].expression.right.value = 'How old are you??'
console.log(generator(ast_code).code)
// 打印 ast_code 的输出
Node {
  type: 'File',
  start: 0,
  end: 33,
  loc: SourceLocation {
    start: Position { line: 1, column: 0, index: 0 },
    end: Position { line: 1, column: 33, index: 33 },
    filename: undefined,
    identifierName: undefined
  },
  errors: [],
  program: Node {
    type: 'Program',
    start: 0,
    end: 33,
    loc: SourceLocation {
      start: [Position],
      end: [Position],
      filename: undefined,
      identifierName: undefined
    },
    sourceType: 'script',
    interpreter: null,
    body: [ [Node], [Node] ],
    directives: []
  },
  comments: []
}

// 修改后的结果
var a;
a = "How old are you??";
console.log('=======解析成AST=======')
const {parse} = require('@babel/parser')
var js_code = `
var a = 1

var b = 2
var c;

console.log(a + b)
`
let ast_code = parse(js_code, {
    sourceType: 'module',//默认为'script'。'unambiguous':尝试推测,若存在ES6的'import'或'export'语法,则推测为'module',否则为'script'
})
console.log(ast_code)

console.log('=======遍历值=======')
const traverse = require('@babel/traverse').default
const visitor = {
    Identifier(path) {
        console.log('name = ' + path.node.name)
    },
    NumericLiteral(path) {
        console.log('value = ' + path.node.value)
    },
}
traverse(ast_code, visitor)
console.log('=======生成js代码=======')

const generator = require('@babel/generator').default(ast_code, {
    retainLines: true,//默认为'false'。保留空行
})
console.log(generator.code)

AST
https://元气码农少女酱.我爱你/0725b07e2f6d/
作者
元气码农少女酱
发布于
2023年5月27日
许可协议