如何设置具有多个源目录和单独编译目标的 Typescript 项目?

Yuk*_*élé 5 typescript tsconfig

我的包裹是这样的:

? tsconfig.json
? src/
? ? index.ts         (import './dependence.ts')
? ? dependence.ts
? example/
  ? index.html
  ? script.ts        (import '../src/index.ts')
Run Code Online (Sandbox Code Playgroud)

我想

  • ./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')
Run Code Online (Sandbox Code Playgroud)

我对所有 tsconfig 选项都有些困惑。
我已经尝试了很多选项,如baseUrl, paths, rootDir, outDir, rootDirs, ... 都没有成功。

vas*_*vas 6

简单。使用单独的tsconfig文件,每个源目录中的一个文件将每个文件建立为单独的项目,并使用 Typescript项目引用来建立example项目和src项目之间的依赖关系。

  1. src/tsconfig.json
{
    "compilerOptions": {
       "rootDir": ".",
       "outDir": "../dist/",
       "composite": true  // required if another project has a reference to this one.
    },
} 
Run Code Online (Sandbox Code Playgroud)
  1. example/tsconfig.json
{
    "compilerOptions": {
      "rootDir": ".",
      "outDir": ".",  // because you want example to compile in place
    },
    "references": [   // declare the dependencies
      { "path": "../src" }  
    ]
}
Run Code Online (Sandbox Code Playgroud)
  1. 使用tsc -b而不是tsc -p用于增量(即更快)构建:

    运行tsc --buildtsc -b简称)将执行以下操作:

    • 查找所有引用的项目
    • 检测它们是否是最新的
    • 以正确的顺序构建过时的项目

    例如

    • tsc -b src 只构建 src
    • tsc -b example 由于依赖关系,将同时构建两者
    • tsc -b src example 如果你想露骨
  2. 如果您想在项目之间共享部分或大部分设置以保持 DRY 或强制执行一致性,您可以:

    • 将另一个tsconfig放在根目录中并将所有常用设置移动到它。
    • 更改每个子配置以扩展根配置:
      "extends": "../tsconfig.json"
      
      Run Code Online (Sandbox Code Playgroud) 如果子配置在树中更深,则调整路径。
  3. 您可以进一步执行第 4 步,并将其用作“一个‘解决方案’tsconfig.json”,如项目参考文档的这一部分所述。这应该使您能够从整个项目根目录构建所有内容tsc -b .

我想我涵盖了你需要的一切。还有的详细解释outDir这个答案,项目引用。如果我遗漏了什么或者您有任何问题,请告诉我。

  • @Yukulélé 我的错!我忘记了“tsconfig”不会自动继承树上的配置(就像其他一些系统一样)。我更新了我的答案...参见#4。 (2认同)