ast入门

PANH 2020-07-05

拓展

JavaScript 教程
ES6 入门教程

百度在线字体编辑器
奇Q在线字体编辑器
fonttools

AST在线解析网站
babel库 GitHub
babel库 docs
Babel插件开发手册

查看JavaScript代码流程
GitHub地址

ast入门

安装

node
https://nodejs.org/zh-cn/

babel

npm install @babel/core

基本框架

const fs = require(‘fs‘);
const {parse} = require("@babel/parser");
const traverse = require("@babel/traverse").default;
const t = require("@babel/types");
const generator = require("@babel/generator").default;

let jscode = fs.readFileSync("./demo.js", {
    encoding: "utf-8"
});
let ast = parse(jscode);

const visitor =
{
  //TODO  write your code here!
}

//some function code

traverse(ast,visitor);
let {code} = generator(ast);
fs.writeFile(‘decode.js‘, code, (err)=>{});

节点含义

使用

变量替换

原代码:

var s=92
var a = s+5
var b=func(1324801, a)

替换后:

var s = 92;
var a = 97;
var b = func(1324801, 97);

ast入门
ast入门

通过 path.evaluate() 来进行计算,替换代码:

const visitor =
{
    "Identifier|BinaryExpression"(path) {
        let {confident, value} = path.evaluate();
        // console.log(path.type, confident, value)
        if (confident) {
            // console.log(path.node);
            path.replaceInline(t.valueToNode(value))
        }
    },
}

构建 BinaryExpression 类型的节点

注释的是不调用库函数创建的方法

const visitor =
{
    "VariableDeclarator"(path){
        const {init} = path.node;
        // let node = {
        //     type: "BinaryExpression",
        //     operator: "*",
        //     left: {
        //         type: "NumericLiteral",
        //         value: 20,
        //     },
        //     right: {
        //         type: "NumericLiteral",
        //         value: 20,
        //     }
        // }
        //
        // init || path.set("init", node)

        init || path.set("init", t.binaryExpression(‘*‘,t.valueToNode(20),t.valueToNode(30)))

    }
}

a[‘length‘] 转换为 a.length

const visitor =
{
    "MemberExpression"(path){
        let property = path.get(‘property‘);
        if(property.isStringLiteral()){
            let value = property.node.value;
            path.node.computed = false;
            property.replaceWith(t.Identifier(value))
        }
    }
}

严格模式

const visitor =
{
    "FunctionExpression"(path){
        let body = path.node.body;
        body.directives[0] = t.directiveLiteral(‘use strict‘)
    }
}

相关推荐