简体   繁体   中英

`Cannot find module` for my own TypeScript module

I have just published a new TypeScript-based module to the NPM registry, ooafs . However, when I try to install it and import it in another TypeScript project, VSCode gives me the following error on the import statement: Cannot find module 'ooafs'.ts(2307) .

This module's source files are compiled to JavaScript to a dist/ folder and definitions ( .d.ts ) are also generated.

Here's the tree of the published module (the one we download when we npm install ):

.
├── dist
│   ├── Entry.d.ts
│   ├── EntryFilter.d.ts
│   ├── EntryFilter.js
│   ├── Entry.js
│   ├── EntryType.d.ts
│   ├── EntryType.js
│   ├── FSTypings.d.ts
│   ├── FSTypings.js
│   ├── index.d.ts
│   └── index.js
├── LICENSE
├── package.json
└── README.md

The package.json does contain the following entries:

{
    "main": "dist/index.js",
    "types": "dist/index.d.ts",
    ...
}

Because the module works normally on Runkit (pure JS), I assume the only problem I have is related to TypeScript, and it's not the first time TypeScript tells me a module doesn't exist when missing declaration files are the only problem.

Am I missing a step in the compilation process? Are my package.json properties wrong?

If you need to see more code, the Github link is at the beginning of the question, and the published module structure can be found here: https://unpkg.com/ooafs@0.1.2/dist/ .

Actually, the problem didn't come from my module (ooafs). It was a problem with the tsconfig.json of the project I was using the module in: The module property must be set to commonjs apparently.

Very late edit: Also, I highly recommend setting esModuleInterop to true which allows you to import non-es6 modules in a more natural manner.

The answer is not the fix, and is certainly not ideal when you have to use top-level awaits (which don't work on commonjs).

You want to make sure your import path is the final file that node will try and load. So you cannot rely on folders resolving to folder/index.js and you cannot rely on giving file names without extensions (give the ".js" extension)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM