【问题标题】:Writing Babel plugin, how to modify code after visitor?写Babel插件,访问后如何修改代码?
【发布时间】:2023-02-08 12:02:39
【问题描述】:
export default function({ types: t }) {
  return {
    pre(state) {
      this.allString = '';
    },
    visitor: {
      StringLiteral(path) {
        this.allString += path.node.value;
      }
    },
    post(state) {
      // It does not work
      state.code = `const allString = '${this.allString}'\n` + state.code;
    }
  };
}

例如,我想在代码中添加一个包含所有字符串的变量,是否可以通过一个插件来完成?

【问题讨论】:

    标签: javascript babeljs transpiler babel-plugin


    【解决方案1】:

    完毕

    post(state) {
      state.ast.program.body.push(t.variableDeclaration('const', [
        t.variableDeclarator(t.identifier('allString'), t.stringLiteral(this.allString))
      ]));
    }
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关如何和/或为何解决问题的额外上下文将提高​​答案的长期价值。你可以在帮助中心找到更多关于如何写出好的答案的信息:stackoverflow.com/help/how-to-answer。祝你好运
    【解决方案2】:

    post方法中的state变量有一个ast属性和一个path属性,您可以使用它们来修改代码。例如:

    export default function({ types: t }) {
      return {
        visitor: {
          // Do preparation work in this visitor
        },
        post(state) {
          state.path.traverse({
            // Do code changes in this one
          })
        }
      };
    }
    

    或者,您可以通过 pre 方法进行检查(因为它与 post 具有相同的签名),然后使用 visitor 进行实际代码更改。

    【讨论】:

      猜你喜欢
      • 2018-04-28
      • 1970-01-01
      • 2019-07-12
      • 2012-03-23
      • 1970-01-01
      • 1970-01-01
      • 2022-11-14
      • 2022-08-07
      • 2010-10-20
      相关资源
      最近更新 更多