【问题标题】: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))
]));
}
【解决方案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 进行实际代码更改。