运行 使用 codemod 时,Babel 插件 addComment 不起作用
Babel plugin addComment doesn't work when ran with codemod
我创建了一个 babel 插件:
module.exports = function (babel) {
const { types: t } = babel;
return {
name: 'addComment',
visitor: {
Program(path, state) {
path.addComment('leading', '@@@ My precious @@@');
path.unshiftContainer('body', t.noop());
}
}
};
}
我希望它应该在模块顶部添加一个注释行// @@@ My precious @@@
,并在注释后添加一个空行。
我运行这个插件用@codemod/cli:
./node_modules/.bin/codemod --plugin ./babel-plugin.js ./transform-me.js
我在源文件中只插入了一个空行,没有注释行。
如果我在 astexplorer.net 中尝试相同的代码,它工作正常。
我尝试添加带有 "comments": true 选项的 .babelrc 文件和带有 --find-babel-config 参数的 运行 codemod。同样的结果。
我做错了什么?
我找到了决定。如果我直接操作评论数组,则插入评论:
function addComment(path, comment) {
const rootNode = path.node.body[0];
if (!rootNode.comments) {
rootNode.comments = [];
}
rootNode.comments.push({
leading: true,
trailing: false,
value: comment,
type: 'CommentLine'
});
}
path.addComment('leading', 'my comment') -> addComment(path, 'my comment')
我创建了一个 babel 插件:
module.exports = function (babel) {
const { types: t } = babel;
return {
name: 'addComment',
visitor: {
Program(path, state) {
path.addComment('leading', '@@@ My precious @@@');
path.unshiftContainer('body', t.noop());
}
}
};
}
我希望它应该在模块顶部添加一个注释行// @@@ My precious @@@
,并在注释后添加一个空行。
我运行这个插件用@codemod/cli:
./node_modules/.bin/codemod --plugin ./babel-plugin.js ./transform-me.js
我在源文件中只插入了一个空行,没有注释行。 如果我在 astexplorer.net 中尝试相同的代码,它工作正常。
我尝试添加带有 "comments": true 选项的 .babelrc 文件和带有 --find-babel-config 参数的 运行 codemod。同样的结果。
我做错了什么?
我找到了决定。如果我直接操作评论数组,则插入评论:
function addComment(path, comment) {
const rootNode = path.node.body[0];
if (!rootNode.comments) {
rootNode.comments = [];
}
rootNode.comments.push({
leading: true,
trailing: false,
value: comment,
type: 'CommentLine'
});
}
path.addComment('leading', 'my comment') -> addComment(path, 'my comment')