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?
CodePudding user response:
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.