1

In my typescript project I need to add the *.js extension when doing imports, otherwise the project will build but it will fail at runtime in the browser because it cannot find the file.

This is what my typescript imports look like:

import {MainApp} from './MainApp.js';

window.onload = () => {
  var app = new MainApp(5);
  app.doSomething();

};

From what I have read (Appending .js extension on relative import statements during Typescript compilation (ES6 modules) for example) it seems a normal thing for typescript that I cannot do this: import {MainApp} from './MainApp.js';

But the thing is that in Angular using typescript I can do this:

import {MainApp} from './MainApp';

So, how it is Angular doing it? There is a way I can replicate that behavior in my non angular, pure typescript project?

Art
  • 163
  • 1
  • 8

1 Answers1

2

Because angular cli first compiles all your source files into fewer files for the browser. All your code from multiple files lands in just one .js file. At compile time the compiler finds the MainApp related file and puts it into the output file.

Whereas the typescript compiler for the most part just removes the TS parts and keeps the TS parts. Otherwise it doesn't touch the files. The browser then at runtime requests all the source .js files.

If you don't want to care about file endings in import you'll need a bundler. There are many different ones like webpack, rollup, parcel, and many more.

RaiderB
  • 100
  • 1
  • 6
  • > If you don't want to care about file endings in import you'll need a bundler. This is the key insight. You only need to add `.js` file extensions to your imports in TS files if you intend to run the compiled JS in a Node runtime environment. Bundlers by their very nature do not need to import anything at runtime because all of your TS source has been collapsed into one output `.js` file. – zippycoder Feb 19 '23 at 10:21