TypeScript: Specify a directory to look for module type definitions

橙三吉。 提交于 2021-01-20 19:07:46

问题


Heyho,

I want to use some javascript libraries in my typescript code for which there are no typings in npm. So I wrote the typings myself and put them in a definitions directory in my source tree. However, I could not get typescript to look in that directory for those modules.

My directory structure looks like this:

+-node_modules
| |
| +-moduleA
| |
| +-moduleB
|
+-src
| |
| +-definitions
| | |
| | +-moduleA.d.ts
| | |
| | +-moduleB.d.ts
| |
| +-ts
|   |
|   + ... all typescript code ...
|
+-tsconfig.json

I tried including the modules in the definitions-directory using

  • include
  • files
  • typeRoots
  • paths

However none of it worked.

Can somebody tell me, how to get typescript to include those typings?

PS: Why is the TypeScript module handling so complicated???


回答1:


{
  "compilerOptions": {
    "typeRoots": [
      "./node_modules/@types",
      "./some-custom-lib"
    ]
  }
}

the typeRoots string array is just for that. In addition to your regular "node_modules/@type", add a custom made typings folder.




回答2:


You can include them with the triple-slash Directives to direct the compiler to use them.

E.g. create an index.d.ts file and put it your definitions folder. There you can include every custom typing you made. It could look like this

/// <reference path="react.patch.d.ts" />
/// <reference path="custom-typings.d.ts" />

Inside the typings file the first line has to be

/// <reference types="nameOfIt" />

Then in your tsconfig.json you include them in the files field e.g.

"files": [
    "definitions/index.d.ts"
  ]


来源:https://stackoverflow.com/questions/45507481/typescript-specify-a-directory-to-look-for-module-type-definitions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!