gpt4 book ai didi

javascript - 带有 jscodeshift 的 Codemod - 从导入中删除逗号

转载 作者:行者123 更新时间:2023-11-30 19:18:16 24 4
gpt4 key购买 nike

我正在尝试编写一个小型 codemod 来重构一些代码。考虑一下我有这样的东西:

import { mod1, mod2, mod3 } from 'package1'
import localMod from 'package2'

我想将其更改为:

import { mod1, mod3 } from 'package1'
import * as mod2 from 'new-package'
import localMod from 'package2'

作为第一步,我尝试删除 mod2从我成功完成的第一行导入,但我无法删除 mod1 之后的逗号.

到目前为止,我的代码片段如下所示:

module.exports = function transformer(file, api) {
const j = api.jscodeshift;
const root = j(file.source);

const reactApolloImports = root
.find(j.ImportDeclaration)
.filter(nodepath => nodepath.value.source.value === "package1")
.find(j.Identifier)
.forEach(nodepath => {
if (nodepath.name === "imported" && nodepath.node.name === "mod2") {
j(nodepath).remove();
}
});

return root.toSource();
};

请帮忙。

最佳答案

不是在 j.ImportDeclaration 中搜索和删除 j.Identifier,而是通过 j.ImportSpecifier 表达式找到它们的父节点。如果删除这些,应该没问题。

如果您将 import { mod1, mod2, mod3 } from 'package1' 语句粘贴到 AST Explorer 中,则更容易理解。

enter image description here

代码:

module.exports = function transformer(file, api) {
const j = api.jscodeshift;
const root = j(file.source);

const reactApolloImports = root
.find(j.ImportDeclaration)
.filter(impDecNodePath => impDecNodePath.value.source.value === "package1")
.forEach(impDecNodePathFiltered => {
j(impDecNodePathFiltered)
// find ImportSpecifier here instead of Identifier
.find(j.ImportSpecifier)
.forEach(impSpecNodePath => {
if (impSpecNodePath.node.imported.name === "mod2") {
j(impSpecNodePath).remove();
}
});
});

return root.toSource();
};

更改输出:

import { mod1, mod3 } from 'package1';
import localMod from 'package2'

希望对您有所帮助。

关于javascript - 带有 jscodeshift 的 Codemod - 从导入中删除逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57764400/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com