【问题标题】:What's the best way to explicitly include types in tsconfig?在 tsconfig 中显式包含类型的最佳方法是什么?
【发布时间】:2018-02-07 09:48:43
【问题描述】:

我遇到了一种情况,我想在我的 node_modules 目录中包含一些但不是全部的 @types。

背景

我的tsconfig.json 看起来像这样:

{
    "compilerOptions": {
        "module": "system",
        "target": "es5",
        "sourceMap": true,
        "allowSyntheticDefaultImports": true,
        "lib": [
            "es2016",
            "dom"
        ]
    },
    "exclude": [
        "node_modules"
    ]
}

我的 @types 通过 npm 安装并位于 node_modules 目录中。

编译器能够找到@types,因为 typeRoots 默认设置为 node_modules/@types。¹或者至少我认为是这样。

问题

我们正在使用 AngularJS,并且我们使用(可能是愚蠢的)由 angular-mocks 提供的 module 变量来引导我们的规范文件。

不过,@types/node 也有一个module,而且它有不同的类型。

现在,每当我编译测试时,每个规范文件都会出现错误:Type 'NodeModule' has no compatible call signatures.

我想避免将每个规范文件从 module 更改为 angular.mock.module。我需要找到一种方法来排除@types/node。

问题

在 tsconfig 中显式包含类型的最佳方式是什么?

可能的解决方案

选项 A:在typesRoots 属性下列出所需的类型,并将“node_modules”标记为exclude。 (这甚至会起作用吗?)

选项 B:根本不使用 typeRoots。使用includeexclude 来配置我想要的@types。 (这行得通)

选项 C:创建一个专用 tsconfig 进行测试,并在专用 tsconfig 中使用选项 A 或选项 B(可能带有扩展)


¹typescript docs 说:

默认情况下,所有可见的“@types”包都包含在您的编译中。任何封闭文件夹的node_modules/@types 中的包都被视为可见;具体来说,这意味着 ./node_modules/@types/../node_modules/@types/../../node_modules/@types/ 等中的包。

【问题讨论】:

    标签: angularjs typescript


    【解决方案1】:

    最好的解决方案是使用types tsconfig 属性:

    "types": ["angular", "angular-mocks", ... etc
    

    这将阻止 tsc 自动枚举您在 node_modules/@types 下的所有文件夹。如果需要,您可以使用配置文件继承,这样您就可以共享所有其他编译器设置而不会重复。

    【讨论】:

    • 啊,是的,隐藏的选项 D :)
    • @RyanCavanaugh 你们有没有想过添加一个excludeTypes: ["foo", "bar"] 属性?这在 monorepo 场景中会有很大帮助,因为按照您的建议手动列出所有内容,但需要更多维护和手动编辑 - 而是包括所有内容并排除某些子项目中不需要的类型。
    • @RyanCavanaugh 如果有机会,请查看at this
    猜你喜欢
    • 2011-06-18
    • 2023-03-11
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多