如何在 Jscodeshift 中正确导出 const

How to properly export a const in Jscodeshift

我正在使用 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();
};

AST

这将导致(注意不需要的新行)

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();
};

astexplorer