从命令行重新组织大型TypeScript项目

5

我有一个中等/大型的TypeScript项目(~500个源文件),我想要进行大规模重组,改变目录结构并移动所有模块。

在VS Code中移动单个文件并更新所有导入很容易:

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

这种重构是使用TypeScript语言服务实现的。使用拖放移动和更新适用于少量文件,但对于大规模的重组,我更愿意编写某种类型的脚本:

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

是否可以以此方式与VS Code或TypeScript语言服务进行交互?还有其他的TypeScript或JavaScript Codemod工具可以帮助解决这个问题吗?

1个回答

4

使用ts-morph的SourceFile.move方法可以很容易地实现:

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中拖放数百个文件要好!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接