So, recently I've come across a situation where I wanted to move some things from an internal lib to the project itself (”inline it”), the thing I wanted to move was just a simple component, but it was imported in a lot of files. Usually I either awk/grep/sed or use Intellij refactor (with preview) reviewing manually all the files (to later review the PR again in github), but this one had a ton of usages, so I tried another approach, which I'm sharing here.
A while ago I've did some static analysis using the typescript compiler on some code in the resolve-barrel-imports babel plugin I have. It was pretty simple, so I've thought that I could use AST analysis to check all imports like this:
import { Foo, Spacing, Bar } from 'our-internal-sdk-lib'
And transform them to the new project import
import { Foo, Bar } from 'our-internal-sdk-lib'
import { Spacing } from '#/src/components/spacing'
Note: those internal sdk imports have a lot of variations, we need a little bit of semantic info to take decisions here, so a simple regex/grep/seed didn't seem fit for me. I'm also not aware of ‘more fit for the job’ tools other than changing the AST itself (I know of codemod, but a whole codemod package for this is not what I wanted)
With the idea in mind, I just need to setup the refactor script. For that, after having a previous experience generating typescript code, I know that using ts-morph will help a lot, so I'll install it and setup a script like this:
// scripts/refactor-imports.ts
import path from 'path';
import { Project } from 'ts-morph';
const project = new Project({
tsConfigFilePath: path.join(__dirname, '../tsconfig.json'),
});
for (const file of project.getSourceFiles()) {
// ...
}
This gives me access to all of my TS project files. Now I need to know what parts of the AST I want to change, for that I'll check things in the ts-ast-viewer: