How can you compile Typescript to work with browsers that support ES modules?
I'm using <script type="module">
with module=es2015
in my tsconfig, but I can't write imports paths that work for the compiler and the runtime.
The browser needs requires fully qualified import paths and Typescript doesn't convert the import extension during compilation.
For example, the following snippet of TS doesn't change during compilation.
import foo from "./foo.ts";
import bar from "./bar";
When it runs in the browser, it emits two network requests for files that don't exist.
GET foo.ts -> (should be) GET foo.js
GET bar -> (should be) GET bar.js
The only way to achieve this at the moment is to use .js
in your TypeScript imports (even though the file is technically .ts
).
// index.ts
import foo from "./foo.js";
// foo.ts
export default "foo";
This only works in TypeScript 2 and more modern versions. See this GitHub issue for more context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With