babeljs - 使用 codemod 运行时,Babel 插件 addComment 不起作用
问题描述
我创建了一个 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')
推荐阅读
- java - Cucumber+Serenity “您可以使用下面的代码片段实现缺少的步骤”
- python - 如何从文本文件中迭代行并执行某些操作?
- java - 可以从头到尾遍历单链表吗?(爪哇)
- mysql - SQL查询,如何改进?
- python - Pandas - 基于来自同一 df 的动态列的新列
- reactjs - 如何在没有身份验证的情况下使用firebase数据库制作登录表单?
- google-cloud-datastore - google-cloud-datastore 是否提供多个数据库
- node.js - 来自文件系统的电子生成器的 AppImage 无法正常工作
- botframework - 我可以使用 bot 编写器发布使用 bot 框架 .NET 核心模板创建的机器人吗
- php - 如何在 AssociationField EasyAdmin 3 中设置默认值