Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular cli: getting it ready for production

I wrote my first Angular 2 application, and I would like to put it onto a test server.

I recently converted it to an Angular-cli project and built it using the command :

ng build --prod

From what I understand, I should then be able to paste the contents of the "/dist" folder onto the test server and run it with

ng serve

However, If the "/dist" folder can run standalone, why am I unable to run it on my pc as a standalone app (ie, I cannot copy the contents of the dist folder to another place on the pc and run it.)

This will actually be the first application I will be putting onto a test/production server, so please bear with me if what I'm asking is silly.

like image 824
Seeker Avatar asked Dec 03 '22 13:12

Seeker


1 Answers

You should not, and I think cannot, use ng serve to publish your build. The files created with ng build can be uploaded to a webserver and served from there.

  1. Run ng build -e=prod --prod --no-sourcemap --aot

Although the latest version of angular-cli defaults to no sourcemaps, it's worth noting here. The -e=prod will make sure it uses the production environment defined inside the environments folder. Last thing is the --aot. If you have no special things going on inside your project, there is a big chance you can have it pre-compiled using the ahead of time compiler. You can however run into problems and you can troubleshoot these using ng serve --aot, or remove the --aot altogether.

  1. You can then continue to copy the contents of the dist folder to your webserver. It's worth noting though that you should make sure that all non existing file requests on the server will redirect to index.html and the url pointing to your application is in the root.

This means for index.html redirection on for instance nginx, you can put this inside your server configuration block:

location / {
  try_files $uri $uri/ /index.html;
}

This is if www.example.com serves the index.html created inside the dist folder. If for some reason you would like to serve your application from a subfolder like, www.example.com/subfolder, then you should modify the <base> tag inside the generated index.html to point to this subfolder.

If you want to test your production build locally, one option is to install lite-server.

npm install -g lite-server

Then navigate in your console to path/to/project/root/dist, and run lite-server. This will create a webserver and open your browser, and serve the generated index.html

If you use nginx and want to be cool and serve the generated .gz files statically, you can place this inside your nginx gzip configuration:

gzip on;
gzip_static on;
like image 197
Poul Kruijt Avatar answered Dec 21 '22 08:12

Poul Kruijt