我正在使用 Jscodeshift 编写我的第一个 codemod。 我当前的目标是导出分配有特定标识符的常量。
因此,如果我将每个名为 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 构建器自己构建命名导出,但真的无法得到它有效。
这里有什么建议吗?
最佳答案
.insertBefore
不是正确的使用方法。这是为了在另一个节点之前插入一个全新的节点。
如何用ExportNamedDeclaration
替换VariableDeclaration
。如果您查看 export const stuff = 4;
的 AST,您可以看到它有一个属性 declaration
,其值为 VariableDeclaration
节点。这使我们的转换变得容易:找到 VariableDeclaration
,创建一个新的 ExportNamedDeclaration
,将其 declaration
属性设置为找到的节点并替换找到的节点节点与新节点。
要了解如何构建节点,我们可以查看 ast-type
's ast definitions .
const constName = "stuff";
module.exports = (fileInfo, api) => {
const j = api.jscodeshift;
return j(fileInfo.source)
.find(j.VariableDeclaration, {
declarations: [
{
id: {
type: "Identifier",
name: constName
}
}
]
})
.replaceWith(p => j.exportDeclaration(false, p.node))
.toSource();
};
关于javascript - 如何在 Jscodeshift 中正确导出 const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57464547/