Sub topic 1
What the Angular CLI does and how to install it
Prerequisites
This chapter assumes you have the following:
- Basic TypeScript syntax and basic HTML and CSS.
- Node.js and npm installed. Angular requires an active or maintenance LTS version of Node.js. Check the supported versions in the Angular documentation for your release.
- Comfort using a terminal.
Check your Node.js and npm versions before you start:
node --version
npm --versionWhat the Angular CLI does
The Angular CLI is a command-line tool that creates, builds and maintains Angular projects. It is the standard way to work with Angular. Its command is ng.
The CLI covers the whole project lifecycle:
| Task | Command |
|---|---|
| Create a workspace | `ng new` |
| Generate components, services and other code | `ng generate` |
| Run a development server | `ng serve` |
| Produce a production build | `ng build` |
| Run unit tests | `ng test` |
| Add a library and configure it | `ng add` |
| Upgrade dependencies and migrate code | `ng update` |
The CLI does not contain all this logic itself. It reads the workspace configuration in angular.json and hands the work to other packages. Schematics generate or change code. Builders run tasks such as building and testing. A later chapter covers both in detail.
Installing the CLI
Install the CLI globally with npm:
npm install -g @angular/cliThe -g flag installs the package for your whole machine, so ng is available in any folder. Confirm the install:
ng versionThe output shows the CLI version, your Node.js version and the installed Angular packages. Outside a workspace, only the CLI and Node.js details appear.
Getting help
Every command documents itself. Use --help to see its options:
ng --help
ng generate --help
ng build --helpUseful options are listed for each command, along with their defaults.
Common errors
ng: command not found: the global npm bin folder is not on yourPATH. Runnpm config get prefixand add itsbinfolder toPATH, or reinstall Node.js with a version manager.EACCESpermission errors during install: npm cannot write to a system folder. Avoidsudo. Fix the npm prefix, or use a Node.js version manager such as nvm.- Unsupported Node.js version: the CLI prints a warning or refuses to run. Switch to a supported LTS release.
Exercise
You run ng version inside a project and the CLI version differs from the one you installed globally. Which version runs your ng build command, and why?
Show answer
The project's local CLI version runs it. When you run ng inside a workspace, the copy in the workspace's node_modules takes precedence over the global install, so each project uses the CLI version it was created with.
Exercise
Name the two kinds of packages the CLI delegates work to, and give one task each handles.
Show answer
Schematics generate or modify code, for example ng generate component. Builders run tasks such as building or testing, for example ng build.