@babel/types ast编译文件

const parse = require('@babel/parser').parse;
const t = require('@babel/types');
const generate = require('@babel/generator').default;
const traverse = require('@babel/traverse').default



const code = '';
const ast = parse(code);


// 1.生成数字 1
const number = t.numericLiteral(1);

// 2.生成二元表达式 1+ 1
const  exp = t.binaryExpression('+',number, number);
// 3.生成变量a
const  variable = t.identifier('a');
// 4.生成变量声明  a = 1 + 1 
const  declarations =  t.variableDeclarator(variable, exp);
// 5.生成变量声明  const a = 1 + 1
const  content = t.variableDeclaration('const', [declarations]);
ast.program.body.push(content);
const output  = generate(ast, {quotes:'single', retainLines : true});
console.log(output.code);  //  const a = 1 + 1 ;


traverse(ast, {
	BinaryExpression(path){
		// console.log(path)
		if(path.node.operator === '+'){
			// path.replaceWith(t.binaryExpression('*', path.node.left, path.node.right))
			path.replaceWithSourceString('a * c');
		}
	}
})

const output2  = generate(ast, {quotes:'single', retainLines : true});
console.log(output2.code);  //  const a = 1 + 1 ;


// -----插入操作
const code2 = `
	const  obj = {
		a: 'a',
		b: 'b'
	}
`

const ast2 = parse(code2);

const property  =  t.objectProperty(t.identifier('c'), t.stringLiteral('c'));

traverse(ast2, {
	ObjectExpression(path){
		
		console.log(path,"xxxx")
		path.pushContainer('properties',  property)
	}
});

const out3 = generate(ast2,{quotes:'single', retainLines:true })

console.log(out3.code,"out3")
原文地址:https://www.cnblogs.com/chengyunshen/p/13043148.html