Skip to content

TypeScript cannot emit valid ES modules due to file extension issue #42151

Closed
@ctjlewis

Description

@ctjlewis

Bug Report

This report is based on the problem covered in #28288 and #16577, but intends to emphasize the fact that this explicitly precludes TS from emitting valid ECMAScript modules.

Issue

Because TS imports do not allow file extensions, but imports in emitted ES modules are not resolved to their relevant file extensions (import ... from './myModule' vs. import ... from './myModule.js'), this output is unusable unless transpiled again with Rollup + Babel or a similar toolkit, no matter how much active care is taken while authoring source code. Executing emitted modules will always throw ERR_MODULE_NOT_FOUND because these sources are not rewritten.

Switching to "module": "commonjs" is not a valid suggestion in this case, as the goal is to get valid ESM output.

⏯ Playground Link

Use yarn test: https://repl.it/@christiantjl/TSImportFileExtensions

💻 Code

tsconfig.json

{
  "compilerOptions": {
    "outDir": "build/",
    
    "target": "esnext",
    "module": "esnext",

    "moduleResolution": "node",
    "esModuleInterop": true
  }
}

index.ts

import { test } from './importMe';
console.log(test); 

build/index.js

import { test } from './importMe';
console.log(test);

🙁 Actual behavior

The import { test } from './importMe' statement is not modified.

🙂 Expected behavior

build/index.js should contain:

import { test } from './importMe.js';
console.log(test);

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions