Fang-Pen Lin
Fang-Pen Lin

Reputation: 14406

Cannot find TypeScript library module under a folder

I am authoring a TypeScript NPM package by following a tutorial here

The code can be found here

https://github.com/envoy/loglevel-file-logger/tree/e4093715b5d06f4c7df9e022f3cbdba160929b02

Then I published the NPM package here

Now, I can install the package via

npm install loglevel-file-logger

and use it in my TypeScript project like this

import setupLogger from 'loglevel-file-logger'

It works perfectly. However, when I am trying to import a non-index file from my package, like this

import FetchBlobWriter from 'loglevel-file-logger/FetchBlobWriter'

Then you will see tsc complains

[ts] Cannot find module 'loglevel-file-logger/FetchBlobWriter'.

If you look into the compiled JS code, you will find that the typing file for FetchBlobWriter is indeed existing at js/FetchBlobWriter.d.ts

Any idea why TypeScript fail to find the module when the .d.ts file is there?

Upvotes: 0

Views: 1984

Answers (1)

Sebastian Sebald
Sebastian Sebald

Reputation: 16856

That's because if you import from the root, like loglevel-file-logger, TS will try to import from node_modules/loglevel-file-logger/index.(js|ts) or will check the the modules main property from the package.json. You set the later to dist/index.js, which is correct.

But, if you want to import a submodule it will the resolve the path from the root folder of the module. Not the folder that may or may not be part of the main property. Meaning, 'loglevel-file-logger/FetchBlobWriter' will resolve to node_modules/loglevel-file-logger/FetchBlobWriter. TS correctly informs you that there is no module/file, since it is hosted inside the dist folder. So importing from 'loglevel-file-logger/dist/FetchBlobWriter' should work.

Here is a article to give you more information about node's path resolution: https://www.bennadel.com/blog/2169-where-does-node-js-and-require-look-for-modules.htm

Upvotes: 3

Related Questions