TypeScript:指定要查找模块类型定义的目录

jsf*_*jsf 8 import module typescript type-definition

Heyho,

我想在我的打字稿代码中使用一些javascript库,在npm中没有任何打字.所以我自己编写了这些打字并将它们放在definitions源代码树的目录中.但是,我无法获取typescript来查看那些模块的目录.

我的目录结构如下所示:

+-node_modules
| |
| +-moduleA
| |
| +-moduleB
|
+-src
| |
| +-definitions
| | |
| | +-moduleA.d.ts
| | |
| | +-moduleB.d.ts
| |
| +-ts
|   |
|   + ... all typescript code ...
|
+-tsconfig.json
Run Code Online (Sandbox Code Playgroud)

我尝试在definitions-directory中使用包含模块

  • include
  • files
  • typeRoots
  • paths

然而,它都没有奏效.

有人可以告诉我,如何获得打字稿以包括那些打字?

PS:为什么TypeScript模块处理如此复杂?

qba*_*ler 7

{
  "compilerOptions": {
    "typeRoots": [
      "./node_modules/@types",
      "./some-custom-lib"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

typeRoots字符串数组就是为了这个.除了常规的"node_modules/@ type"之外,还要添加自定义的typings文件夹.

  • 只要我的模块定义中没有任何导入语句,这似乎就可以工作。但如果没有导入,我就无法正确输入我的模块。 (2认同)

Mur*_*göz 5

您可以将它们包含在三斜杠指令中,以指示编译器使用它们。

例如,创建一个index.d.ts文件并将其放在您的定义文件夹中。您可以在其中包括您进行的所有自定义键入。它可能看起来像这样

/// <reference path="react.patch.d.ts" />
/// <reference path="custom-typings.d.ts" />
Run Code Online (Sandbox Code Playgroud)

在类型文件中,第一行必须是

/// <reference types="nameOfIt" />
Run Code Online (Sandbox Code Playgroud)

然后在您tsconfig.jsonfiles字段中包括它们,例如

"files": [
    "definitions/index.d.ts"
  ]
Run Code Online (Sandbox Code Playgroud)