TypeScript ES modules incompatible with browser and Node.js · Issue #33306 · microsoft/TypeScript (original) (raw)
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.
B.
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:
- Nothing. End-user maintains a post-process that either modifies the outputted import specifiers, or modifies the outputted file locations.
- TypeScript adds a new --module value ESBrowser, which transforms the output import specifiers to have .js extension.
- TypeScript adds a new option --outputExtension which when false or 'remove', strips the extension from the outputted file.