Skip to content

TypeScript inappropriately resolves directory imports in ESM mode, that fail at runtime (in Node, but probably all ESM environments). #61057

Closed
@RobertSandiford

Description

@RobertSandiford

🔎 Search Terms

ESM "directory import" "directory imports"

🕗 Version & Regression Information

Behaves this way for all versions tested on TSPlayground using module: ES*
Behaves this way in a local project with TS 4 and 5, and module: Node16 (moduleResolution: Node16)
I reviewed the FAQ for entries about directory imports and ESM

⏯ Playground Link

Playground

A repro repository is here: https://github.com/RobertSandiford/ts-esm-dir-import-example
After cloning run pnpm i && pnpm run dev
I recommend this over the playground link because you can see the runtime errors.

💻 Code

the package 'i-have-a-dir-and-main' has this file structure:
dist
--index.js
--dir
----index.js

package.json includes:
"type": "module"
"main": "dist/index.js"

An importing project may look like this. This compiles but fails at runtime:

import 'i-have-a-dir-and-main' // OK. Resolves to the "main" export, dist/index.js
import 'i-have-a-dir-and-main/dist/dir' // Fails at runtime.
                                        // TS resolves this to /dist/dir/index.js,
                                        // at runtime this is an invalid directory import

🙁 Actual behavior

TS resolves the import 'i-have-a-dir-and-main/dist/dir' to i-have-a-dir-and-main/dist/dir/index.js, but this is not valid in ESM. Directory imports are not permitted (outside of exceptions like a node legacy behaviour flag)

Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import 'C:\xxx\ts-dir-import-repro\node_modules\i-have-a-dir-and-main\dist\dir' is not supported resolving ES modules imported from C:\xxx\ts-dir-import-repro\dist\index.js
Did you mean to import "i-have-a-dir-and-main/dist/dir/index.js"?
    at finalizeResolution (node:internal/modules/esm/resolve:259:11)
    at moduleResolve (node:internal/modules/esm/resolve:933:10)

🙂 Expected behavior

TSC to fail to resolve the import 'i-have-a-dir-and-main/dist/dir' when in an ESM mode (import resolution: Node*, type module, or import resolution: ES*) and report an import error.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions