Reorganize large TypeScript project from the command line

Viewed 141

I have a medium/large TypeScript project (~500 source files) and I'd like to do a large-scale reorganization, changing the directory structure and moving all the modules around.

It's easy to move a single file in VS Code and update all the imports:

Moving a file to a subdirectory and updating imports in VS Code

This refactor is implemented using the TypeScript Language Service. Doing the move and update using drag and drop works well for a small number of files, but for a mass reorganization, I'd rather write out some kind of script:

old/path/to/file.ts --> new/path/newfile.ts
old/path/to/olddir --> new/path/to/newdir

Is it possible to interact with VS Code or the TypeScript Language Service in this way? Are there other TypeScript or JavaScript codemod tools that can help with this?

1 Answers

This turns out to be pretty straightforward using ts-morph's SourceFile.move method:

const project = new Project({ tsConfigFilePath });
const sourceFile = project.getSourceFileOrThrow('/path/to/file.ts');
sourceFile.move('newFileName.ts');
// or:
// sourceFile.moveToDirectory('/some/dir');

I put together a small tool called ts-mover to consume roughly the list of moves format described in the question (the first line is the path to tsconfig.json):

$ cat moves.txt
path/to/tsconfig.json
src/oldname.ts --> src/newname.ts
src/file.ts --> src/newmodule/file.ts
src/file2.ts --> src/newmodule/

$ npx ts-mover moves.txt
Moving src/oldname.ts --> src/newname.ts
  (Be patient, the first move takes the longest.)
  elapsed: 455 ms
Moving src/file.ts --> src/newmodule/file.ts
Moving src/file2.ts --> src/newmodule/file2.ts
Saving changes to disk...

It's a little slower than I'd like, especially for large projects, but it definitely beats dragging & dropping hundreds of files in VS Code!

Related