DEV Community

Vimalraj Selvam
Vimalraj Selvam

Posted on

2 2

Codemod with jscodeshift help needed

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'
Enter fullscreen mode Exit fullscreen mode

and I wanted to change this to:

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

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();
};
view raw transform.js hosted with ❤ by GitHub

Please help.

Top comments (1)

Collapse
 
rajasegar profile image
Rajasegar Chandran • Edited

Vimal, you are removing just the Identifiers from the Specifiers, you need to remove the actual import specifiers

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!