BLOG POSTS
Angular CLI Reference Guide

Angular CLI Reference Guide

The Angular CLI has become the backbone of modern Angular development, serving as your primary tool for generating, building, testing, and deploying Angular applications. Whether you’re spinning up a quick prototype or managing enterprise-scale applications, mastering the CLI commands and options can dramatically improve your development workflow. This comprehensive guide breaks down the essential Angular CLI commands, their practical applications, and advanced usage patterns that every Angular developer should know, from project initialization to production deployment strategies.

Understanding Angular CLI Architecture

The Angular CLI operates through a workspace-based architecture where everything revolves around the angular.json configuration file. This file defines projects, build targets, and tool options that determine how your applications are processed. The CLI leverages webpack under the hood for bundling, uses TypeScript for compilation, and integrates with various development tools seamlessly.

The workspace structure follows a predictable pattern:

my-workspace/
├── angular.json
├── package.json
├── src/
│   ├── app/
│   ├── assets/
│   └── environments/
├── e2e/
└── node_modules/

Each CLI command operates within this context, understanding project boundaries and configuration inheritance. The CLI uses schematics – templates that define how code should be generated – making it extensible and customizable for team-specific requirements.

Essential CLI Commands Reference

Here’s a comprehensive breakdown of the most frequently used Angular CLI commands with their practical applications:

Command Purpose Common Options Use Case
ng new Create new workspace –routing, –style, –strict Project initialization
ng generate Generate code –dry-run, –skip-tests Component/service creation
ng serve Development server –port, –open, –prod Local development
ng build Build application –prod, –aot, –source-map Production builds
ng test Run unit tests –watch, –browsers Testing workflow
ng lint Code linting –fix, –force Code quality

Project Setup and Configuration

Creating a new Angular project with optimal settings requires understanding the initialization options. Here’s how to set up projects for different scenarios:

Basic project creation:

ng new my-app --routing --style=scss --strict

Enterprise project with additional configuration:

ng new enterprise-app \
  --routing \
  --style=scss \
  --strict \
  --package-manager=npm \
  --skip-git=false \
  --create-application=false

The --create-application=false option creates a workspace without an initial application, useful when you plan to add multiple applications or libraries later.

Adding applications to existing workspace:

ng generate application admin-panel --routing --style=scss
ng generate application user-dashboard --routing --style=css

This approach allows you to manage multiple related applications within a single workspace, sharing dependencies and build configurations.

Code Generation Mastery

The ng generate command (or ng g shorthand) is probably your most-used CLI command. Understanding its nuances can save significant development time:

Component generation with full options:

ng g component feature/user-profile \
  --change-detection=OnPush \
  --style=scss \
  --skip-tests=false \
  --export=true

Service generation with provider configuration:

ng g service core/services/auth \
  --skip-tests=false

Feature module with routing:

ng g module features/dashboard \
  --routing \
  --route=dashboard \
  --module=app

The CLI automatically updates import statements and module declarations, reducing boilerplate and potential errors. For complex applications, use the --dry-run flag to preview changes before applying them:

ng g component shared/data-table --dry-run

Development Server Configuration

The development server offers extensive configuration options for different development scenarios:

Basic development server:

ng serve --port 4200 --open

Development with proxy configuration:

ng serve --proxy-config proxy.conf.json

Create proxy.conf.json for API integration during development:

{
  "/api/*": {
    "target": "http://localhost:3000",
    "secure": true,
    "changeOrigin": true,
    "logLevel": "debug"
  }
}

Serving specific project in workspace:

ng serve admin-panel --port 4201

Production-like development build:

ng serve --configuration=production

This serves your application with production optimizations enabled, useful for debugging production-specific issues locally.

Build Optimization Strategies

Understanding build configurations helps optimize applications for different deployment scenarios:

Production build with full optimization:

ng build --configuration=production \
  --source-map=false \
  --stats-json

Development build with source maps:

ng build --source-map=true --watch

Analyzing bundle size:

ng build --stats-json
npx webpack-bundle-analyzer dist/my-app/stats.json

Custom build configurations can be defined in angular.json for different environments:

"configurations": {
  "staging": {
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.staging.ts"
      }
    ],
    "optimization": true,
    "sourceMap": false,
    "buildOptimizer": true
  }
}

Testing and Quality Assurance

The CLI provides comprehensive testing capabilities out of the box:

Unit testing with different browsers:

ng test --browsers=Chrome
ng test --browsers=ChromeHeadless --watch=false

End-to-end testing:

ng e2e
ng e2e --port 4299 --host localhost

Code coverage reporting:

ng test --code-coverage --watch=false

This generates detailed coverage reports in the coverage/ directory, essential for maintaining code quality standards.

Linting with automatic fixes:

ng lint --fix

Advanced CLI Usage and Customization

Power users can extend CLI functionality through custom schematics and builders:

Installing third-party schematics:

ng add @angular/material
ng add @ngrx/store
ng add @angular/pwa

Creating custom schematics:

npm install -g @angular-devkit/schematics-cli
schematics blank --name=my-schematic

Using workspace analytics:

ng analytics on
ng update --all --allow-dirty

Extracting i18n messages:

ng extract-i18n --output-path src/locale

Performance Optimization Commands

Several CLI commands help optimize application performance:

Differential loading for modern browsers:

ng build --configuration=production

This automatically generates ES5 and ES2015+ bundles, serving appropriate versions based on browser capabilities.

Service worker integration:

ng add @angular/pwa
ng build --prod

Lazy loading route generation:

ng g module feature/lazy-feature --route lazy-feature --module app.module

Common Issues and Troubleshooting

Here are solutions to frequently encountered CLI problems:

  • Node version conflicts: Use ng version to check compatibility and consider using nvm for version management
  • Memory issues during builds: Increase Node.js heap size with node --max-old-space-size=8192 ./node_modules/@angular/cli/bin/ng build
  • Port conflicts: Use ng serve --port 0 to automatically assign available ports
  • Cache issues: Clear npm cache with npm cache clean --force and delete node_modules
  • Global vs local CLI conflicts: Uninstall global CLI and use npx: npx @angular/cli@latest new my-app

Debugging build issues:

ng build --verbose --progress
ng build --source-map=true

Integration with Development Tools

The Angular CLI integrates seamlessly with modern development workflows:

Docker integration:

# Dockerfile
FROM node:16-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN ng build --configuration=production
EXPOSE 4200
CMD ["ng", "serve", "--host", "0.0.0.0"]

CI/CD pipeline example:

npm ci
ng lint
ng test --browsers=ChromeHeadless --watch=false --code-coverage
ng build --configuration=production
ng e2e --protractor-config=e2e/protractor-ci.conf.js

IDE integration commands:

ng config -g cli.packageManager npm
ng config projects.my-app.schematics.@schematics/angular.component.style scss

Best Practices and Tips

Follow these practices to maximize CLI effectiveness:

  • Always use --dry-run flag when testing new schematics or complex generations
  • Leverage workspace configurations for consistent team settings
  • Use ng update regularly to keep dependencies current
  • Configure proxy settings for seamless API integration during development
  • Implement custom builders for specialized build requirements
  • Use environment-specific configurations for different deployment targets
  • Monitor bundle sizes regularly using --stats-json option
  • Automate testing and linting in pre-commit hooks

The Angular CLI continues evolving with each release, adding new capabilities and optimizations. Stay updated with the official Angular CLI documentation for the latest features and best practices. For comprehensive command references, check the CLI command help documentation which provides detailed information about all available options and flags.



This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.

This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.

Leave a reply

Your email address will not be published. Required fields are marked