Search code examples
angularbuildproductionangular-cli

Angular 2 with CLI - build for production


I have freshly installed angular-cli 1.0.0.beta.17 (latest one), start new project, able to serve project on port 4200 with no problems - just standard "app works!" message.

However when I try to build for production this empty and generic application by using command ng build --prod I do not have main.*.js file created at all and have a few screens of warnings like:

  • Dropping unused function...
  • Site effects in initialization...
  • etc

This is a brand new empty project - I did not have a chance to break anything yet...

How to build production version ?


Solution

  • Updated for Angular v16+

    # Prod - these are equivalent
    ng build --configuration=production
    ng build --c=production
    ng build 
    
    # Dev - and so are these
    ng build --configuration=development
    ng build --c=development
    

    More flag settings here https://angular.io/cli/build


    Legacy code below this line


    Updated for Angular v6+

    # Prod - these are equivalent
    ng build --configuration=production
    ng build --c=production
    ng build --prod=true
    
    # Dev - and so are these
    ng build --configuration=development
    ng build --c=development
    ng build --prod=false
    ng build
    


    Per Angular-cli's github wiki v2+, these are the most common ways to initiate a dev and production build

    # Prod these are equivalent
    ng build --target=production --environment=prod
    ng build --prod --env=prod
    ng build --prod
    
    # Dev and so are these
    ng build --target=development --environment=dev
    ng build --dev --env=dev
    ng build --dev
    ng build
    

    There are different default flags that will affect --dev vs --prod builds.

    Flag                 --dev      --prod
    --aot                false      true
    --environment        dev        prod
    --output-hashing     media      all
    --sourcemaps         true       false
    --extract-css        false      true
    

    --prod also sets the following non-flaggable settings:

    • Adds service worker if configured in .angular-cli.json.
    • Replaces process.env.NODE_ENV in modules with the production value (this is needed for some libraries, like react).
    • Runs UglifyJS on the code.

    Original:

    I need to do some troubleshooting in order to get AOT working. When I ran:

    ng build --prod --aot=false

    I would get will return a error similar to

    Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory'
    

    Originally, I had to do some project refactoring to get AOT to work. However, they may be a fix if you are encountering this error. Try

    npm i [email protected]

    https://github.com/angular/angular-cli/issues/7113