Home > other >  Compile Typescript to run in the browser using modules
Compile Typescript to run in the browser using modules

Time:03-26

With Javascript I can use modules (i.e. import and export statements) and subdivide the code in different files and have such code run in the browser.

Let's take the simplest example made of 3 files: my-function-js.js, main-js.js and page-js.html

my-function-js.js

export function myFunctionJs() {
  console.log("here I am, a pure Javascript function");
}

main-js.js

import { myFunctionJs } from "./my-function-js.js";

myFunctionJs();

page-js.html

<!DOCTYPE html>
<html>
  <body>
    <script type="module" src="./main-js.js"></script>
  </body>
</html>

If I try to do the same with Typescript (the same code in files with the .ts extensions) I fail because the compiler generates all kinds of "module related" depending on the module option given to the compiler but is not able to simply maintain the code like it is and have it work like Javascript works with modules.

I realize this is a sort of theoretical question, that we should used bundlers and so on, but I was just curious to know if there is a simple way to make modules work in the browser just using the Typescript compiler.

CodePudding user response:

when running tsc on the theoretical code / files in your question, it generates the desired output which works fine in the browser, so long as you set the target in your tsconfig.json to es6 or higher, since the features you're trying to use were introduced in es6:

  "target": "es6",

the only trick of it though is that in your ts file you need to include the .js extension you're expecting to be generated in your import, or you need to include no extension and configure your web server to be able to figure out what the browser is asking for when it requests the file with no extension.

  • Related