Build Your First Angular Website

Angular CLI: Serving and Building for Production

We saw how to serve our application in the last lesson using ng serve. Let's dive into this a bit more and see what the Angular CLI provides to us.

Serving Our Application

By using ng serve we saw that five files are generated for us.

ng serve

You'll see the five files are:

  • inline.bundle.js: A tiny file that helps webpack load resources
  • main.bundle.js: The bulk of our Angular application
  • polyfills.bundle.js: The things needed to let Angular work in older browsers
  • styles.bundle.js: The styles!
  • vendor.bundle.js: The Angular specific libraries

https://i.imgur.com/VGaUADm.png

Building For Production

ng serve works for serving our application for development purposes. What about for production? If we look into our package.json file, we can see that there are scripts we can use:

"scripts": {
  "ng": "ng",
  "start": "ng serve",
  "build": "ng build --prod",
  "test": "ng test",
  "lint": "ng lint",
  "e2e": "ng e2e"
},

The build script uses the Angular CLI's ng build with the --prod flag. Let's try that now. We can do it one of two ways:

# using the npm scripts
npm run build

# using the cli directly
ng build --prod

This time we are given four files instead of the five. The --prod flag tells Angular to make our application much smaller in size.

https://i.imgur.com/FAHYS3l.png

Notice the file size differences!

The dist folder

The build command also creates a new folder called dist for distribution. These are the files we can host on a server and our Angular app will load up.

That's all it takes to deploy an Angular application:

https://i.imgur.com/3b9SZrA.png

We would just need to have our server using Apache or nginx serve all requests to this index.html file. Angular will take care of the rest.