Skip to content

Cannot find module or its corresponding type declaration when "main" has cjs file extension #45496

Description

Bug Report

When importing a module that sets package.json#main = "dist/index.cjs", tsc outputs Cannot find module ... or its corresponding type declaration. Manually renaming the file to dist/index.js and updating package.json#main = "dist/index.js" fixes it.

In Node, using cjs extensions for CommonJS output is mandatory when using package.json#type = "module". Note that this package has other exports which are not picked up by TypeScript (but could be exploited):

// package.json of the imported module..."sideEffects": false,
"type": "module",
"source": "src/index.js",
"main": "dist/index.cjs",
"module": "dist/index.module.js",
"esmodule": "dist/index.modern.js",
"umd:main": "dist/index.umd.js",
"unpkg": "dist/index.umd.js",
"exports": {
".": {
"browser": "./dist/index.module.js",
"umd": "./dist/index.umd.js",
"require": "./dist/index.cjs",
"default": "./dist/index.modern.js"
}
},
...

Here is my tsconfig.json (I am only using TypeScript to check types):

// tsconfig.json of the importing module
{
"$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": {
"noEmit": true,
"target": "esnext",
"module": "esnext",
"lib": ["esnext", "dom"],
"allowJs": true,
"checkJs": true,
"jsx": "preserve",
"incremental": true,
"strict": true,
"noImplicitAny": false,
"noImplicitThis": false,
"strictNullChecks": false,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noImplicitOverride": false,
"noPropertyAccessFromIndexSignature": false,
"noUncheckedIndexedAccess": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"allowUnreachableCode": false,
"moduleResolution": "node",
"resolveJsonModule": true,
"types": ["meteor", "mocha"],
"esModuleInterop": true,
"preserveSymlinks": true,
"allowSyntheticDefaultImports": true
},
"include": [
"types/**/*",
"server/**/*",
"client/**/*",
"imports/**/*"
]
}

Please explain to me what is my mistake. I would be happy to know how to make Node, ESM, and TypeScript work together.

🔎 Search Terms

  • Cannot find module or its corresponding type declaration
  • main
  • cjs
  • file extension

🕗 Version & Regression Information

This is the behavior in every version I tried, and I reviewed the FAQ for entries about cjs/CommonJS.

⏯ Playground Link

⚠️PS: The error spit out by the playground tool might be irrelevant (although identical).

Playground link with relevant code

💻 Code

import{range}from'@iterable-iterator/range';console.log(range(10**9).has(10**8));

🙁 Actual behavior

❌ Cannot find module '@iterable-iterator/range' or its corresponding type declarations. (2307)

🙂 Expected behavior

It should not report a missing module error.

Metadata

Metadata

Labels

Needs InvestigationThis issue needs a team member to investigate its status.

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions