'Understanding type definition files in Node JS and TypeScript
I'm trying to understand how TypeScript projects resolve the import of modules installed via npm and their type definition files.
As far as I know (and following the TypeScript documentation), there are two ways TypeScript uses for module resolution :
With a relative path : It will check then on the current directory if the module files exist (
myModule.js
,myModule.tsx
andmyModule.d.ts
) or in a directory namedmyModule
(containingindex.js
,index.tsx
andindex.d.ts
)With a non-relative path : It will check the import following NodeJS behavior by checking in the
node_modules
folder in the same way it did for the references with relative path, and jumping a directory if not found
So it seems pretty easy to understand. What I don't understand, is how it resolves the type definition files when imported using npm install @types/myModule
. I need to understand this in order to structure correctly my project, and also understand why sometimes my modules / type definitions are not found.
I don't understand how it knows that "the folder in node_modules/@types/myModule
contains the type definition for myModule
: Where is stored the information that it must check in that folder ?
Bonus : What is the best way to import and manage type definition files ? Is it better to install the @types
package for the related module, or to download the file.d.ts
and place it in the module folder in node_modules
?
Any help and / or references are greatly appreciated.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|