作用域内变量替换

https://www.jianshu.com/p/a3857fa5c899

 

 

const fs = require('fs');
const { parse } = require("@babel/parser");
const traverse = require("@babel/traverse").default;
const t = require("@babel/types");
const generator = require("@babel/generator").default;

let jscode = `

var a = window;
let b = a.btoa("Hello,AST")

`;

let ast = parse(jscode);

const visitor = {
    VariableDeclarator(path) {
        const { id, init } = path.node;
        // 类型是Identifier, 并且name属性为 window
        if (!t.isIdentifier(init, { name: "window" })) { return }
        let name = id.name
        let scope = path.scope;
        const binding = scope.getBinding(name); // 获取windows在当前节点的作用域中的值
        if (!binding || binding.constantViolations.length !== 0) { return };
        scope.rename(name, 'window')  //重点,上边有笔记
        path.remove()
    }
}




traverse(ast, visitor);
let { code } = generator(ast);
console.log(code);

 

posted @ 2022-01-07 20:08  AngDH  阅读(44)  评论(0编辑  收藏  举报