问题描述
我有一个中/大型 TypeScript 项目(约 500 个源文件),我想进行大规模重组,更改目录结构并移动所有模块。
在 VS Code 中移动单个文件并更新所有导入很容易:
此重构是使用 TypeScript Language Service 实现的。使用拖放进行移动和更新对于少量文件很有效,但对于大规模重组,我宁愿写出某种脚本:
old/path/to/file.ts --> new/path/newfile.ts
old/path/to/olddir --> new/path/to/newdir
是否可以通过这种方式与 VS Code 或 TypeScript 语言服务交互?是否有其他 TypeScript 或 JavaScript codemod 工具可以帮助解决这个问题?
解决方法
事实证明,使用 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');
我整理了一个名为 ts-mover
的小工具来大致使用问题中描述的移动格式列表(第一行是 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...
它比我想要的要慢一点,特别是对于大型项目,但它绝对胜过在 VS Code 中拖放数百个文件!