标签:gen 创建 Edito 框架 img 基本框架 lin npm conf
AST在线解析网站
babel库 GitHub
babel库 docs
Babel插件开发手册
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);
通过 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‘)
}
}
标签:gen 创建 Edito 框架 img 基本框架 lin npm conf
原文地址:https://www.cnblogs.com/gaoyongjian/p/13246736.html