1

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

AST

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

export
const stuff = 4;

如果将此源提供给脚本,这也将严重失败。

在:

// hey
const stuff = 4;

出去:

export
// hey
const stuff = 4;

我非常确信这n.insertBefore("export");确实是罪魁祸首,我想使用 jscodeshift 构建器自己构建命名导出,但真的无法让它工作。

这里有什么建议吗?

4

1 回答 1

4

.insertBefore不是正确的使用方法。这是为了在另一个节点之前插入一个全新的节点。

怎么想VariableDeclaration. _ ExportNamedDeclaration如果您查看 AST,export const stuff = 4;您会发现它有一个属性declaration,其值为VariableDeclaration节点。这使我们的转换变得容易:找到VariableDeclaration,创建一个新ExportNamedDeclaration的 ,将它的declaration属性设置为找到的节点并用新节点替换找到的节点。

要了解如何构建节点,我们可以查看ast-typeast 定义

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

探索者

于 2019-10-17T09:26:39.550 回答