在codemod中使用babel-types库中的commentBlock函数来添加注释。示例代码如下:
const { parseSync, transformFromAstSync } = require('@babel/core');
const { commentBlock } = require('@babel/types');
function myTransform(file, api) {
const ast = parseSync(file.source);
const { types: t } = api;
// 通过遍历AST树并找到需要添加注释的node
const newAst = t.visit(ast, {
enter(path) {
if (path.isVariableDeclaration() && path.node.kind === 'const') {
// 使用babel-types库中的commentBlock函数添加注释
path.addComment(
'leading',
' This const variable should not be mutated ',
true
);
}
return path;
},
});
return transformFromAstSync(newAst, null, {
presets: ['@babel/preset-env'],
}).code;
}
module.exports = myTransform;