【问题标题】:how to setup a Typescript project with multiple source dirs and separate compile destinations?如何设置具有多个源目录和单独编译目标的 Typescript 项目?
【发布时间】:2021-06-30 13:04:36
【问题描述】:

我的包裹是这样的:

┌ 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 选项都有点困惑。
我用baseUrlpathsrootDiroutDirrootDirs等选项尝试了很多东西,但都没有成功。

【问题讨论】:

    标签: typescript tsconfig


    【解决方案1】:

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

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

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

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

      例如

      • tsc -b src 只是构建 src
      • tsc -b example 将因为依赖而构建两者
      • tsc -b src example 如果你想表达的话
    2. 如果您想在项目之间共享部分或大部分设置以保持 DRY 或强制一致性,您可以:

      • 在根目录中添加另一个tsconfig 并将所有常用设置移至其中。
      • 将每个子配置更改为 extend 根配置:
        "extends": "../tsconfig.json"
        
        如果子配置在树中更深,则调整路径。
    3. 您可以进一步执行第 4 步并将其用作“解决方案”tsconfig.json,如项目参考文档的this section 中所述。这应该使您能够使用 tsc -b . 从整个项目根目录构建所有内容

    我想我涵盖了你需要的一切。有a detailed explanation of outDir and project references in this answer。如果我遗漏了什么或有任何问题,请告诉我。

    【讨论】:

    • 谢谢!这适用于两个 tsconfig.json 文件,但如果我在根目录中添加第三个文件,则会忽略根设置。我应该运行哪个命令?我应该在根 conf 和子 conf 之间添加引用吗?
    • @Yukulélé,不会忽略根设置。最接近代码的设置(即在同一目录中)将覆盖目录树上更远的任何设置。因此,如果您想要通用设置,则需要在要从根配置继承的非根配置中取出设置。这一切都在文档中。你应该阅读它们。
    • 引用仅适用于对另一个项目具有构建依赖关系的项目。如果您仅将根配置用于共享设置,那么不,它不需要引用。您可以将根配置设置为构建目标,将srcexample 作为依赖项,然后说tsc -b . 来构建根。但你真的应该在设置之前了解所有这些是如何工作的。请阅读文档。否则请保持简单,就像我在上面帮助你的那样。
    • @Yukulélé 我的错!我忘记了tsconfig 不会自动继承树上的配置(就像其他一些系统一样)。我更新了我的答案...见 #4。
    • 您是否阅读了我的第二条评论并按照手册中的说明进行操作?即您是否在根配置中“将文件设置为空数组”。您是否正确设置了 compositereferences 属性(所有三个 tsconfig 都需要这两者的不同组合)。
    猜你喜欢
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 2016-08-02
    • 2020-03-09
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多