看别人ast混淆代码 挺6的学习一下
学习第一步:
let a,b=1; // 注释 var obj = { "name":1+3*2, "func":function add(a,b){ let a1=3; return a+b } } function add(a,v){ return a+v; } let xx; xx = 12;View 源代码
let fs = require("fs");//读取文件 let parser = require("@babel/parser");//解析语法树 let types = require("@babel/types");//获取类型 let generator = require("@babel/generator").default;//语法树转换成代码 let traverse = require("@babel/traverse").default;//遍历语法树 let jscode = fs.readFileSync("./input.js", { encoding: "utf-8" }); let ast = parser.parse(jscode, { sourceType: "module" }); let one = types.variableDeclaration("let",[ types.variableDeclarator(types.identifier("a"),null), types.variableDeclarator(types.identifier("b"),types.numericLiteral(120)) ]); console.log(generator(one).code); let two = types.variableDeclaration("var",[ types.variableDeclarator(types.identifier("obj"),types.objectExpression([ types.objectProperty(types.stringLiteral("name"),types.binaryExpression("+",types.numericLiteral(1),types.binaryExpression("*",types.numericLiteral(3),types.numericLiteral(2)))), types.objectProperty(types.stringLiteral("func"),types.functionExpression(null,[types.identifier("a"),types.identifier("b")],types.blockStatement([ types.variableDeclaration("let",[types.variableDeclarator(types.identifier("a1"),types.numericLiteral(3))]), types.returnStatement(types.binaryExpression("+",types.identifier("a"),types.identifier("b"))) ]))) ])) ]); console.log(generator(two).code); let three = types.functionDeclaration(types.identifier("add"),[types.identifier("a"),types.identifier("v")],types.blockStatement([types.returnStatement(types.binaryExpression("+",types.identifier("a"),types.identifier("v")))])); console.log(generator(three).code); let four = types.variableDeclaration("let",[types.variableDeclarator(types.identifier("xx"),null)]); console.log(generator(four).code); let five = types.expressionStatement(types.assignmentExpression("=",types.identifier("xx"),types.numericLiteral(12))); console.log(generator(five).code);View 用ast语法树实现和它一样的代码
效果:
标签:numericLiteral,code,generator,ast,学习,let,identifier,types From: https://www.cnblogs.com/inkser/p/17793044.html