Keywords: Angular | Angular CLI | Development Server
Abstract: This article provides a comprehensive guide on how to specify a default port for the development server in Angular CLI, covering methods for different versions including the latest @angular/cli@9.x and above, historical configurations, and alternative approaches such as command-line flags and npm scripts. It aims to help developers avoid manually passing the --port flag every time when using ng serve.
Introduction
When using Angular CLI for development, the ng serve command by default starts the server on port 4200. However, developers often need to change this port due to conflicts or preferences. This article explores various methods to specify a default port, eliminating the need for manual flags.
Latest Method for Angular CLI 9.x and Above
For versions 9.x and above, the configuration is done in the angular.json file. Inside the project configuration, under the serve options, you can set the port as shown below:
"projects": {
"my-cool-project": {
"architect": {
"serve": {
"options": {
"port": 1337
}
}
}
}
}This method allows per-project configuration and is the recommended approach for modern Angular CLI projects.
Historical Methods
For older versions, different files were used. In the final version of @angular/cli, the angular-cli.json file contained a defaults section:
"defaults": {
"serve": {
"port": 1337
}
}Even earlier, in angular-cli@1.0.0-beta.22-1, an .ember-cli file was used, as the server was derived from Ember CLI:
{
"port": 1337
}These methods are legacy and may not apply to current setups.
Alternative Approaches
Aside from configuration files, you can specify the port directly when running the command:
ng serve --port 1337To simplify this, you can add a script to your package.json:
"scripts": {
"start": "ng serve --port 1337"
}This allows running npm start to start the server on the desired port, making it easier for team collaboration.
Additional Configuration Options
The configuration files support other options such as host, liveReload, and environment. Refer to the official Angular documentation for a complete list.
Conclusion
By using configuration files or npm scripts, developers can efficiently set a default port for the Angular CLI development server, enhancing workflow and reducing manual input.