Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile Typescript to native browser ES modules

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
like image 626
Dan Prince Avatar asked Aug 30 '25 16:08

Dan Prince


1 Answers

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.

like image 60
Dan Prince Avatar answered Sep 02 '25 18:09

Dan Prince