Date: September 15, 2022
Introduction
The Angular CLI is the backbone of Angular development, but beyond the common commands like ng serve and ng build, it packs powerful hidden features that can dramatically improve your productivity. In this post, we’ll explore some lesser-known Angular CLI tricks, how to create custom schematics, manage environment-specific builds efficiently, and automate tasks with custom builders.
1. CLI Command Shortcuts and Tricks
a. Use ng g as a shortcut for ng generate
ng g c my-component
Quickly generate components, services, modules, and more.
b. Generate files in specific paths
ng g s services/api --flat
Generates a service without creating a separate folder.
2. Custom Schematics: Automate Repetitive Tasks
Schematics allow you to automate code generation beyond Angular’s defaults.
Why create custom schematics?
- Enforce project-specific coding standards
- Generate boilerplate for your architecture
- Speed up repetitive tasks like creating feature modules
Basic example of custom schematic
You can scaffold a custom schematic with:
npm install -g @angular-devkit/schematics-cli
schematics blank --name=my-schematic
Then define your templates and logic in the generated schematic project. Once published, use it as:
ng g my-org:my-schematic
3. Environment-Specific Builds: Optimize with File Replacements
Angular’s CLI supports replacing files based on the build configuration. For example, you might want different API endpoints for development and production.
In angular.json:
"configurations": {
"production": {
"fileReplacements": [{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}]
}
}
Then build for production:
ng build --configuration production
This automatically swaps your environment variables.
4. Custom Builders: Extending CLI Build Processes
Builders are like plugins that extend or replace Angular CLI’s default build or serve behavior.
Example use case: Running pre/post build scripts
You can write a custom builder to run scripts before or after building your app.
To use a custom builder:
- Create or install a builder package.
- Update your
angular.jsonto reference it.
Example snippet:
"architect": {
"build": {
"builder": "my-custom-builder:build",
"options": { ... }
}
}
5. Additional CLI Tips
a. Inspect the project with ng config
ng config projects.my-app.architect.build.options.outputPath
Check CLI config values without opening JSON files.
b. Use ng update for automatic dependency upgrades
Keep your Angular version and dependencies fresh with:
ng update @angular/core @angular/cli
Conclusion
Unlocking these hidden Angular CLI features can save you hours by automating routine tasks, streamlining builds, and maintaining clean codebases. Take time to explore schematics and custom builders—they’re powerful tools that scale with your projects.