Skip to content

TypeScript ES modules incompatible with browser and Node.js #33306

Closed
@pauldraper

Description

@pauldraper

Typescript is incompatible with ECMAScript modules, as implemented in browsers and Node.js (the two most common ES runtimes).

TypeScript Version: 3.6.2 (Node.js 12.7.0)

Search Terms: ES2015 module, browser, Node.js

Code

https://github.com/pauldraper/ts-es-import

yarn install
yarn run build

A.

yarn run run

B.

yarn run serve

Browse to http://localhost:8080 with ES2015-compatible browser (Chrome, Edge, Firefox, Safari).

Expected behavior:

A.

"Hello world" is printed in the console.

B.

"Hello world" is printed.

Actual behavior:

A.

GET http://localhost:8080/out/lib net::ERR_ABORTED 404 (Not Found)

B.

Error: Cannot find module '/home/paul/dev/pauldraper/typescript-nodejs/out/lib' imported from /home/paul/dev/pauldraper/typescript-nodejs/out/main.js

Playground Link:

Related Issues:


The issue is that while Node's CommonJS modules use a list of implicit file extensions, Node and browsers require the extension.

And neither Typescript's classic nor node resolution strategies permit a file extension. This choice allows tsc to not touch the import specifiers, as the .ts/.d.ts/.tsx/.js/.jsx/.json relationship stays the same before and after compilation.

Solutions:

  1. Nothing. End-user maintains a post-process that either modifies the outputted import specifiers, or modifies the outputted file locations.

  2. TypeScript adds a new --module value ESBrowser, which transforms the output import specifiers to have .js extension.

  3. TypeScript adds a new option --outputExtension which when false or 'remove', strips the extension from the outputted file.

Metadata

Metadata

Assignees

Labels

RescheduledThis issue was previously scheduled to an earlier milestoneWorking as IntendedThe behavior described is the intended behavior; this is not a bug

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions