ast入门
拓展
AST在线解析网站
babel库 GitHub
babel库 docs
Babel插件开发手册
安装
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);
通过 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‘) } }
相关推荐
EdwardSiCong 2020-11-23
yungpheng 2020-10-19
jipengx 2020-11-12
橄榄 2020-11-03
lyqdanang 2020-11-02
wservices 2020-10-30
onepiecedn 2020-10-29
数据人 2020-10-26
dfphoto 2020-10-16
hackerlpy 2020-09-07
tianyayi 2020-08-16
Dullonjiang 2020-08-15
fengling 2020-08-15
wordmhg 2020-08-06
guotiaotiao 2020-08-06
zhangsyi 2020-07-28
千锋 2020-07-27
ahnjwj 2020-07-28