ES6 Rewriting Imports in JavaScript and TypeScript
Rudolf Olah

Rudolf Olah @rudolfolah

About: Eng Manager / Staff Software Eng

Location:
Canada
Joined:
Jun 9, 2019

ES6 Rewriting Imports in JavaScript and TypeScript

Publish Date: Nov 4 '23
0 3

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

Comments 3 total

  • Home Officer
    Home OfficerNov 6, 2023

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

    • Rudolf Olah
      Rudolf OlahNov 7, 2023

      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.

      • Home Officer
        Home OfficerNov 7, 2023

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

Add comment