常量计算
作者:互联网
const parser = require("@babel/parser"); const traverse = require("@babel/traverse").default; // 将js代码转换成AST // const { parse } = require("@babel/parser"); // 用来遍历AST中的节点 // const traverse = require("@babel/traverse").default; // AST转换成js const generator = require("@babel/generator").default; // 用来判断节点类型和生成新的节点 const types = require("@babel/types"); const jscode = ` var a = !![],b = 'Hello ' + 'world' + '!',c = 2 + 3 * 50,d = Math.abs(-200) % 19,e = true ? 123:456; `; let ast = parser.parse(jscode); const constantFold = { "BinaryExpression|UnaryExpression|ConditionalExpression|CallExpression|MemberExpression|SequenceExpression"(path) { if(path.isUnaryExpression({operator:"-"}) || path.isUnaryExpression({operator:"void"})) { return; } const {confident,value} = path.evaluate(); if (value == "Infinity" || !confident) return; path.replaceInline(types.valueToNode(value)); }, } traverse(ast, constantFold); let { code } = generator(ast); console.log(code);
标签:traverse,const,常量,babel,require,parser,计算,path 来源: https://www.cnblogs.com/angdh/p/15758042.html