【问题标题】:TypeScript `tsc` not picking up tsconfig.json inside a subdirectory?TypeScript `tsc` 没有在子目录中获取 tsconfig.json?
【发布时间】:2020-11-02 07:09:38
【问题描述】:

我的目录结构如下:

.
├── tsconfig.json ("module": "CommonJS")
└── foo/
    ├── node-file.ts
    └── bar/
        ├── browser-file.ts
        └── tsconfig.json ("module": "esnext")

tsconfig.jsonmodule 设置为CommonJS,因为我希望我的大部分文件都为Node 编译。但在bar 内部,我希望文件编译为JavaScript 模块,所以我将module 设置为esnext

现在,当我从根目录运行 tsc 时,我希望 node-file.ts 编译为 CommonJS 模块,browser-file.ts 编译为 JavaScript 模块。但这不是我得到的。看来tsc完全无视foo/bar/tsconfig.json,只捡根tsconfig.json

(我在开发时也使用tsc --watch,所以我试图避免运行两个不同的tsc 进程来编译两个不同的目标。在我看来,运行一个带有嵌套@ 的tsc 987654339@ 文件应该会给我想要的结果。)

有人知道我做错了什么吗?

【问题讨论】:

  • TypeScript 只使用一个tsconfig.json 并且不会自动将子目录的tsconfig.json 用于那里的文件。你可能想看看project references
  • 我不知道项目引用是否允许我为每个目录设置不同的模块类型,我会进一步研究它。但是感谢您纠正了我对编译器如何工作的错误假设。随意发布这个作为答案,我会接受它。

标签: typescript


【解决方案1】:

TypeScript 只使用一个tsconfig.json,并且不会自动将子目录的tsconfig.json 用于那里的文件。但是,您可以为此使用project references

创建一个这样的目录结构:

.
├── tsconfig.json
├── tsconfig.settings.json (optional)
└── foo/
    ├── node-file.ts
    ├── tsconfig.json ("module": "commonjs")
    └── bar/
        ├── browser-file.ts
        └── tsconfig.json ("module": "esnext")

tsconfig.json

{
  "files": [],
  "references": [
    {"path": "./foo"},
    {"path": "./foo/bar"}
  ]
}

这是根tsconfig.json。当你在根目录下运行tsc --build(见下文)时,TypeScript 将构建引用的项目./foo/tsconfig.json./foo/bar/tsconfig.json

"files": [] 是为了阻止意外的tscs 没有--build 尝试编译根目录中的所有内容,这会出错但会在可能不正确的位置创建多个.js 文件。

tsconfig.settings.json(可选)

{
  "compilerOptions": {
    "strict": true,
    "noImplicitReturns": true
  }
}

您可以将foofoo/bar 通用的配置放在extends 上扩展此配置以减少重复。请注意,此处的所有相对路径在扩展时都将相对于tsconfig.settings.json 进行解析,因此"outDir": "dist" 之类的内容可能无法按预期工作。

foo/tsconfig.json

{
  "extends": "../tsconfig.settings.json",
  "exclude": ["bar/**/*.ts"],
  "compilerOptions": {
    "module": "commonjs"
  }
}

这是 CommonJS 文件的配置。它还扩展了通用配置并排除了foo/bar 中的文件。

foo/bar/tsconfig.json

{
  "extends": "../../tsconfig.settings.json",
  "compilerOptions": {
    "module": "esnext"
  }
}

这与foo 的配置非常相似。


建筑

要同时编译foofoo/bar,使用根目录下的构建模式:

tsc --build # or tsc -b
# Watch mode:
tsc --build --watch # or tsc -b -w

来自the handbook

期待已久的功能是 TypeScript 项目的智能增量构建。在 3.0 中,您可以将 --build 标志与 tsc 一起使用。这实际上是 tsc 的新入口点,其行为更像是构建协调器,而不是简单的编译器。

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

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

您可以为tsc -b 提供多个配置文件路径(例如tsc -b src test)。就像tsc -p一样,如果配置文件名为tsconfig.json,则不需要指定配置文件名本身。

您还可以编译单个项目:

tsc -b foo # or cd foo && tsc
tsc -b foo/bar # or cd foo/bar && tsc

请注意,这是一些仅构建标志和you cannot override compiler options with command-line arguments

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 2020-03-05
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多