我正在使用 Jscodeshift 编写我的第一个 codemod。我目前的目标是导出一个分配了特定标识符的 const。
因此,如果我针对每个名为stuff
的变量,它将在脚本运行后被命名导出。
在:
const stuff = 4;
出去:
export const stuff = 4;
这是我所拥有的精简版。它有点工作,但它看起来很脆弱并且有许多缺点。
const constName = "stuff";
module.exports = (fileInfo, api) => {
const j = api.jscodeshift;
const root = j(fileInfo.source);
const declaration = root.find(j.VariableDeclaration, {
declarations: [
{
id: {
type: "Identifier",
name: constName
}
}
]
});
declaration.forEach(n => {
n.insertBefore("export");
});
return root.toSource();
};
这将导致(注意不需要的新行)
export
const stuff = 4;
如果将此源提供给脚本,这也将严重失败。
在:
// hey
const stuff = 4;
出去:
export
// hey
const stuff = 4;
我非常确信这n.insertBefore("export");
确实是罪魁祸首,我想使用 jscodeshift 构建器自己构建命名导出,但真的无法让它工作。
这里有什么建议吗?