[英]Babel plugin addComment doesn't work when ran with codemod
I've created a babel plugin:我创建了一个 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());
}
}
};
}
I expect that it should add a comment line // @@@ My precious @@@
to the top of the module and add a blank line after the comment.我希望它应该在模块顶部添加一个注释行
// @@@ My precious @@@
并在注释后添加一个空行。
I ran this plugin with @codemod/cli:我用@codemod/cli 运行了这个插件:
./node_modules/.bin/codemod --plugin ./babel-plugin.js ./transform-me.js
And I got only a blank line inserted in the source file and no comment line.而且我在源文件中只插入了一个空行,没有注释行。 If I try the same code in the astexplorer.net, it works fine.
如果我在 astexplorer.net 中尝试相同的代码,它工作正常。
I've tried to add.babelrc file with "comments": true option and run codemod with the --find-babel-config param.我尝试使用 "comments": true 选项添加.babelrc 文件并使用 --find-babel-config 参数运行 codemod。 The same result.
同样的结果。
What did I do wrong?我做错了什么?
I've found a decision.我找到了一个决定。 If I manipulate comments array directly, then comments are inserted:
如果我直接操作评论数组,则插入评论:
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.