31 lines
853 B
JavaScript
31 lines
853 B
JavaScript
//usage:讲述@babel/type
|
|
|
|
import {traverse,types} from "@babel/core";
|
|
import {parse} from "@babel/parser";
|
|
import CodeGenerator from "@babel/generator";
|
|
// import * as t from "@babel/types";
|
|
|
|
|
|
|
|
const code = "const a = 1";
|
|
let ast = parse(code);
|
|
|
|
traverse(ast, {
|
|
VariableDeclaration(path) {
|
|
const a = types.identifier("a")
|
|
let init = types.binaryExpression(
|
|
"+",
|
|
types.identifier("a"),
|
|
types.numericLiteral(1)
|
|
);
|
|
let declarator = types.variableDeclarator(types.identifier("b"), init);
|
|
let declaration = types.variableDeclaration("const", [declarator]);
|
|
path.insertAfter(declaration);
|
|
path.stop();
|
|
},
|
|
}
|
|
);
|
|
const output = CodeGenerator.default(ast, {
|
|
retainLines: true,
|
|
}).code;
|
|
console.log(output); |