DEV Community

Rudolf Olah
Rudolf Olah

Posted on

ES6 Rewriting Imports in JavaScript and TypeScript

Sometimes "find and replace all" doesn't work in software development. In fact, it definitely does not work for import declarations in JavaScript and TypeScript!

Say you moved a function somewhere and you want to change the path it is imported from. In this example, you can see there are multiple different orders to the import and potentially newlines to deal with:

// multi-line import
import {
  AnotherFeature,
  CoolFeature,
  OneMoreFeature,
} from "./features";

// one line import
import { CoolFeature } from "./features";

// one line import, default
import Cool from "./features";

// one line import with multiple and different ordering
import { AnotherFeature, CoolFeature, OneMoreFeature } from "./features";
import { CoolFeature, AnotherFeature } from "./features";
import { OneMoreFeature, CoolFeature } from "./features";
Enter fullscreen mode Exit fullscreen mode

How is that possible with a humble find/replace? Sure, you could try to craft a regex, but it could miss a few scenarios and become incorrect code.

However, Abstract Syntax Tree could do the job. It would read the lines of JavaScript, parse them and search for the parts of the syntax tree that indicate an import declaration.

Anyway, I wrote a small tool for rewriting imports so that you change an import to point from a top-level directory to another specific path, or to point to another path. It uses glob to search for files, so it can be customized to search across all paths for rewriting the imports. It uses recast for the AST, the Abstract Syntax Tree and rewrite.

https://github.com/rudolfolah/rewrite-imports-es6

Top comments (3)

Collapse
 
wolframkriesing profile image
Home Officer

the refactoring function of some IDEs also does moving functions, including proper import rewrites quite well (I am using IntelliJ for this successfully)

Collapse
 
rudolfolah profile image
Rudolf Olah

Intellij is quite good at refactoring; although I haven't tried it for moving a function from one project to another package within a multi-repo project.

Collapse
 
wolframkriesing profile image
Home Officer

not sure if a multi-repo project works, but within an IntelliJ Project it works fine, I do that quite often.