跳到主要内容

将 var 转化为 let

2024年11月10日
柏拉文
越努力,越幸运

一、认识


二、实现


const babelParser = require("@babel/parser");
const babelTraverse = require("@babel/traverse");
const babelGenerator = require("@babel/generator");

const { parse } = babelParser;
const { default: traverse } = babelTraverse;
const { default: generate } = babelGenerator;

const transformVarToLet = (sourceCode) => {
const ast = parse(sourceCode);

traverse(ast, {
VariableDeclaration(path) {
if (path.node.kind === "var") {
path.node.kind = "let";
}
},
});
return generate(ast).code;
};

const sourceCode = `var a = lang("嘻嘻"); var b = lang("哈哈"); var c = () => { var d = 3; return d;};`;
const result = transformVarToLet(sourceCode);
console.log(result);