zoukankan      html  css  js  c++  java
  • @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")
    
  • 相关阅读:
    React Native解决Android的WebView无法执行injectedJavaScript代码
    Java中BitSet使用(转)
    Java StringTokenizer分割字符串
    【git】git常用命令简介
    【细说Java】方法重载的简单介绍
    【细说Java】Java封箱拆箱的一些问题
    【Java解惑】表达式问题
    【细说Java】Java的重写与隐藏
    【细说Java】揭开Java的main方法神秘的面纱
    Maven简介
  • 原文地址:https://www.cnblogs.com/chengyunshen/p/13043148.html
Copyright © 2011-2022 走看看