I'm trying to write a small codemod to refactor some of the code. Consider I've somethihng like this:
import { mod1, mod2, mod3 } from 'package1'
import localMod from 'package2'
and I wanted to change this to:
import { mod1, mod3 } from 'package1'
import * as mod2 from 'new-package'
import localMod from 'package2'
As a first step, I'm trying to remove mod2
from the 1st line of import which I did successfully, but I'm not able to remove the comma after mod1
.
My code snippet so far look like this:
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();
};
Please help.
Instead of searching for and removing
j.Identifier
insidej.ImportDeclaration
, find their parent nodes byj.ImportSpecifier
expression instead. If you remove these, you should be fine.It is more understandable, if you paste your
import { mod1, mod2, mod3 } from 'package1'
statement into AST Explorer.Code:
Changed output:
Hope, it helps.