如何设置具有多个源目录和单独编译目标的Typescript项目?
我的包裹是这样的:
? tsconfig.json
? src/
? ? index.ts (import './dependence.ts')
? ? dependence.ts
? example/
? index.html
? script.ts (import '../src/index.ts')
我想
./src/*.ts编译在./dist/*.js./example/*.ts编译在./example/*.js
运行后tsc,我希望我的包看起来像这样:
? tsconfig.json
? src/
? ? index.ts (import './dependence.ts')
? ? dependence.ts
?!dist/
? ?!index.js (import './dependence.js')
? ?!dependence.js
? example/
? index.html
? script.ts (import '../src/index.ts')
?!script.js (import '../dist/index.js')
我对所有 tsconfig 选项都有些困惑。
我已经尝试了很多选项,如baseUrl, paths, rootDir, outDir, rootDirs, ... 都没有成功。
回答
简单。使用单独的tsconfig文件,每个源目录中的一个文件将每个文件建立为单独的项目,并使用 Typescript项目引用来建立example项目和src项目之间的依赖关系。
src/tsconfig.json:
{
"compilerOptions": {
"rootDir": ".",
"outDir": "../dist/",
"composite": true // required if another project has a reference to this one.
},
}
example/tsconfig.json:
{
"compilerOptions": {
"rootDir": ".",
"outDir": ".", // because you want example to compile in place
},
"references": [ // declare the dependencies
{ "path": "../src" }
]
}
-
使用
tsc -b而不是tsc -p用于增量(即更快)构建:运行
tsc --build(tsc -b简称)将执行以下操作:- 查找所有引用的项目
- 检测它们是否是最新的
- 以正确的顺序构建过时的项目
例如
tsc -b src只构建 srctsc -b example由于依赖关系,将同时构建两者tsc -b src example如果你想露骨
-
如果您想在项目之间共享部分或大部分设置以保持 DRY 或强制执行一致性,您可以:
- 将另一个
tsconfig放在根目录中并将所有常用设置移动到它。 - 更改每个子配置以扩展根配置:
"extends": "../tsconfig.json"如果子配置在树中更深,则调整路径。
- 将另一个
-
您可以进一步执行第 4 步,并将其用作“一个‘解决方案’tsconfig.json”,如项目参考文档的这一部分所述。这应该使您能够从整个项目根目录构建所有内容
tsc -b .
我想我涵盖了你需要的一切。还有的详细解释outDir这个答案,项目引用。如果我遗漏了什么或者您有任何问题,请告诉我。