Babel插件里怎么修改AST节点的值?

百里瑞雪 阅读 4

我在写一个Babel插件,想把代码里的某个字符串字面量替换成别的内容,但改完没生效,是不是哪里搞错了?

比如这段代码:

const msg = 'hello world';
console.log(msg);

我试过在 visitor 里直接赋值 node.value = ‘hi’,但输出还是原来的 ‘hello world’,难道不能这么改?

我来解答 赞 5 收藏
二维码
手机扫码查看
1 条解答
A. 春艳
A. 春艳 Lv1
你这是 visitor 的第一个参数搞错了,它接收的是 path 不是 node,正确写法是用 path.node.value 或者 path.replaceWith()

直接改值的话这样写:
module.exports = function({ types: t }) {
return {
visitor: {
StringLiteral(path) {
if (path.node.value === 'hello world') {
path.node.value = 'hi';
}
}
}
};
};


更推荐用 path.replaceWith(t.stringLiteral('hi')),替换整个节点更稳,避免一些边界情况的坑。
点赞
2026-03-02 15:19