How Angular2 and Webpack start your application

The people working on Angular 2+ have given a lot of thought to the end javascript, the javascript files that land on your production server. They have made it so simple, just run "ng build --prod" and copy the /dist folder to production. But let trace some of how this works.

There is a file angluar.json in the route of every angular project. This has 2 entries:

"index": "src/index.html",

"main": "src/main.ts",

The first line tells Webpack that your starting html page is index.html. After it does its minification and bundeling, webpack places links to the scripts in this file. In majority of the cases, just running the production build, will generate a dist folder with the index.html. At the bottom of this index.html are the following entries:

<script type="text/javascript" src="runtime.randomnumber.js"></script>

<script type="text/javascript" src="es2015-polyfills.randomnumber.js" nomodule><script>

<script type="text/javascript" src="polyfills.randomnumber.js"></script>

<script type="text/javascript" src="main.randomnumber.js"></script>

main.randomnumber.js represent our application. This comes from the second entry "src/main.ts" in angluar.json. Tracing this a bit futher. The main.ts files is where our angular application boots up. It should have an entry like the below:

platformBrowserDynamic.bootstrapModule(AppModule)
.catch(err => console.error(err));

This is the line that boots up our starting Module, in this case AppModule. The AppModule than can load other modules as dependencies in the form of imports and components it intends to use in the declarations array. 

The last piece of the puzzle, bootstrapping the first component. This can be found in the boostrap array of the AppModule and the default entry is AppComponent. This is the component that can than load other components in the <router-outlet></router-outlet> tag. The bootstrapping section can bootstrap more than one components, but they all have to be on the index.html, else the application will throw an error like:

Error: "The selector "app-root" did not match any elements"

Hopefully the boot up process and how this ties into webpack makes more sense

Schubert

Other topics you might like: