美文网首页
babel学习

babel学习

作者: y_7539 | 来源:发表于2022-03-16 14:33 被阅读0次
    let obj = {
        name: 'lanqian',
        add: function(a, b){
            return a + b + 1000;
        },
        mul: function(a, b){
            return a * b + 1000;
        }
    }
    
    const fs = require('fs');
    const parser = require("E:/nodejs/npm_global_modules/node_modules/@babel/parser")
    const traverse = require("E:/nodejs/npm_global_modules/node_modules/@babel/traverse").default
    const t = require("E:/nodejs/npm_global_modules/node_modules/@babel/types")
    const generator = require("E:/nodejs/npm_global_modules/node_modules/@babel/generator").default
    
    const jscode = fs.readFileSync("./demo.js", {encoding: "utf-8"});
    let ast = parser.parse(jscode)
    
    //ast操作
    // let code = generator(ast).code
    // console.log(ast)
    
    //遍历节点,替换参数
    const updateParamNameVisitor = {
        Identifier(path){
            if (path.node.name == this.paramName){
                path.node.name = "x"
            }
        }
    }
    const visitor = {
        FunctionExpression(path){
            const paramName = path.node.params[0].name;
            path.traverse(updateParamNameVisitor, {
                paramName
            });
        }
    }
    traverse(ast, visitor)
    //语法树转成代码
    let code = generator(ast).code
    console.log(code)
    // fs.writeFile('./demoNew.js', code, (err) =>{})
    

    相关文章

      网友评论

          本文标题:babel学习

          本文链接:https://www.haomeiwen.com/subject/zyspdrtx.html