docs: update documentation to use ng generate config and ng generate environments (#48757)

In Angular CLI 15.1  new sub commands to generate configuration and environments files were added. This commit updates several docs to mention these commands.

Closes #48364

PR Close #48757
This commit is contained in:
Alan Agius
2023-01-17 12:34:39 +00:00
committed by Andrew Kushnir
parent fe6a2bd9e2
commit 42ca9c0b02
3 changed files with 143 additions and 190 deletions
+125 -121
View File
@@ -6,15 +6,23 @@ This page discusses build-specific configuration options for Angular projects.
## Configuring application environments
You can define different named build configurations for your project, such as *staging* and *production*, with different defaults.
You can define different named build configurations for your project, such as `development` and `staging`, with different defaults.
Each named configuration can have defaults for any of the options that apply to the various [builder targets](guide/glossary#target), such as `build`, `serve`, and `test`.
The [Angular CLI](cli) `build`, `serve`, and `test` commands can then replace files with appropriate versions for your intended target environment.
### Configure environment-specific defaults
A project's `src/environments/` folder contains the base configuration file, `environment.ts`, which provides a default environment.
You can add override defaults for additional environments, such as production and staging, in target-specific configuration files.
Using the Angular CLI, start by running the [generate environments command](cli/generate#environments-command) shown here to create the `src/environments/` directory and configure the project to use these files.
<code-example format="shell" language="shell">
ng generate environments
</code-example>
The project's `src/environments/` directory contains the base configuration file, `environment.ts`, which provides configuration for `production`, the default environment.
You can override default values for additional environments, such as `development` and `staging`, in target-specific configuration files.
For example:
@@ -27,7 +35,7 @@ For example:
environment.ts
</div>
<div class="file">
environment.prod.ts
environment.development.ts
</div>
<div class="file">
environment.staging.ts
@@ -41,7 +49,7 @@ For example:
<code-example format="typescript" language="typescript">
export const environment = {
production: false
production: true
};
</code-example>
@@ -52,18 +60,6 @@ For example, the following adds a default for a variable to the default environm
<code-example format="typescript" language="typescript">
export const environment = {
production: false,
apiUrl: 'http://my-api-url'
};
</code-example>
You can add target-specific configuration files, such as `environment.prod.ts`.
The following content sets default values for the production build target:
<code-example format="typescript" language="typescript">
export const environment = {
production: true,
apiUrl: 'http://my-prod-url'
@@ -71,9 +67,21 @@ export const environment = {
</code-example>
You can add target-specific configuration files, such as `environment.development.ts`.
The following content sets default values for the development build target:
<code-example format="typescript" language="typescript">
export const environment = {
production: false,
apiUrl: 'http://my-api-url'
};
</code-example>
### Using environment-specific variables in your app
The following application structure configures build targets for production and staging environments:
The following application structure configures build targets for `development` and `staging` environments:
<div class="filetree">
<div class="file">
@@ -99,7 +107,7 @@ The following application structure configures build targets for production and
environment.ts
</div>
<div class="file">
environment.prod.ts
environment.development.ts
</div>
<div class="file">
environment.staging.ts
@@ -122,20 +130,21 @@ The following code in the component file \(`app.component.ts`\) uses an environm
<code-example format="typescript" language="typescript">
import { Component } from '&commat;angular/core';
import { environment } from './../environments/environment';
import { Component } from '&commat;angular/core';
import { environment } from './../environments/environment';
&commat;Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor() {
console.log(environment.production); // Logs false for default environment
&commat;Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor() {
console.log(environment.production); // Logs false for development environment
}
title = 'app works!';
}
title = 'app works!';
}
</code-example>
@@ -152,36 +161,37 @@ For example:
<code-example format="json" language="json">
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
&hellip;
"configurations": {
"development": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.development.ts"
}
],
&hellip;
</code-example>
This means that when you build your production configuration with `ng build --configuration production`, the `src/environments/environment.ts` file is replaced with the target-specific version of the file, `src/environments/environment.prod.ts`.
This means that when you build your development configuration with `ng build --configuration development`, the `src/environments/environment.ts` file is replaced with the target-specific version of the file, `src/environments/environment.development.ts`.
You can add additional configurations as required.
To add a staging environment, create a copy of `src/environments/environment.ts` called `src/environments/environment.staging.ts`, then add a `staging` configuration to `angular.json`:
<code-example format="json" language="json">
"configurations": {
"production": { &hellip; },
"staging": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.staging.ts"
}
]
"configurations": {
"development": { &hellip; },
"production": { &hellip; },
"staging": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.staging.ts"
}
]
}
}
}
</code-example>
@@ -200,20 +210,23 @@ You can also configure the `serve` command to use the targeted build configurati
<code-example format="json" language="json">
"serve": {
"builder": "&commat;angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "your-project-name:build"
},
"configurations": {
"production": {
"browserTarget": "your-project-name:build:production"
"serve": {
"builder": "&commat;angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "your-project-name:build"
},
"staging": {
"browserTarget": "your-project-name:build:staging"
"configurations": {
"development": {
"browserTarget": "your-project-name:build:development"
},
"production": {
"browserTarget": "your-project-name:build:production"
},
"staging": {
"browserTarget": "your-project-name:build:staging"
}
}
}
},
},
</code-example>
@@ -245,8 +258,8 @@ You can specify size budgets for the entire app, and for particular parts.
Each budget entry configures a budget of a given type.
Specify size values in the following formats:
| Size value | Details |
|:--- |:--- |
| Size value | Details |
| :-------------- | :-------------------------------------------------------------------------- |
| `123` or `123b` | Size in bytes. |
| `123kb` | Size in kilobytes. |
| `123mb` | Size in megabytes. |
@@ -257,7 +270,7 @@ When you configure a budget, the build system warns or reports an error when a g
Each budget entry is a JSON object with the following properties:
| Property | Value |
|:--- |:--- |
| :------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| type | The type of budget. One of: <table> <thead> <tr> <th> Value </th> <th> Details </th> </tr> </thead> <tbody> <tr> <td> <code>bundle</code> </td> <td> The size of a specific bundle. </td> </tr> <tr> <td> <code>initial</code> </td> <td> The size of JavaScript needed for bootstrapping the application. Defaults to warning at 500kb and erroring at 1mb. </td> </tr> <tr> <td> <code>allScript</code> </td> <td> The size of all scripts. </td> </tr> <tr> <td> <code>all</code> </td> <td> The size of the entire application. </td> </tr> <tr> <td> <code>anyComponentStyle</code> </td> <td> This size of any one component stylesheet. Defaults to warning at 2kb and erroring at 4kb. </td> </tr> <tr> <td> <code>anyScript</code> </td> <td> The size of any one script. </td> </tr> <tr> <td> <code>any</code> </td> <td> The size of any file. </td> </tr> </tbody> </table> |
| name | The name of the bundle \(for `type=bundle`\). |
| baseline | The baseline size for comparison. |
@@ -316,13 +329,7 @@ Internally, the Angular CLI uses the below `browserslist` configuration which ma
Firefox ESR
</code-example>
To override the internal configuration, add a new file named `.browserslistrc`, to the project directory, that specifies the browsers you want to support:
<code-example format="none" language="text">
last 1 Chrome version
last 1 Firefox version
</code-example>
To override the internal configuration, run [`ng generate browserslist`](cli/generate#config-command), which generates a `.browserslistrc` configuration file in the the project directory.
See the [browserslist repository](https://github.com/browserslist/browserslist) for more examples of how to target specific browsers and versions.
@@ -357,9 +364,9 @@ For example, to divert all calls for `http://localhost:4200/api` to a server run
<code-example format="json" language="json">
&hellip;
"architect": {
"serve": {
&hellip;
"architect": {
"serve": {
"builder": "&commat;angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "your-application-name:build",
@@ -442,27 +449,25 @@ Proxy log levels are `info` \(the default\), `debug`, `warn`, `error`, and `sile
You can proxy multiple entries to the same target by defining the configuration in JavaScript.
Set the proxy configuration file to `proxy.conf.js` \(instead of `proxy.conf.json`\), and specify configuration files as in the following example.
Set the proxy configuration file to `proxy.conf.mjs` \(instead of `proxy.conf.json`\), and specify configuration files as in the following example.
<code-example format="javascript" language="javascript">
const PROXY_CONFIG = [
{
context: [
"/my",
"/many",
"/endpoints",
"/i",
"/need",
"/to",
"/proxy"
],
target: "http://localhost:3000",
secure: false
}
]
module.exports = PROXY_CONFIG;
export default [
{
context: [
'/my',
'/many',
'/endpoints',
'/i',
'/need',
'/to',
'/proxy'
],
target: 'http://localhost:3000',
secure: false
}
];
</code-example>
@@ -476,7 +481,7 @@ In the CLI configuration file, `angular.json`, point to the JavaScript proxy con
"builder": "&commat;angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "your-application-name:build",
"proxyConfig": "src/proxy.conf.js"
"proxyConfig": "src/proxy.conf.mjs"
},
&hellip;
@@ -488,21 +493,19 @@ If you need to optionally bypass the proxy, or dynamically change the request be
<code-example format="javascript" language="javascript">
const PROXY_CONFIG = {
"/api/proxy": {
"target": "http://localhost:3000",
"secure": false,
"bypass": function (req, res, proxyOptions) {
if (req.headers.accept.indexOf("html") !== -1) {
console.log("Skipping proxy for browser request.");
return "/index.html";
}
req.headers["X-Custom-Header"] = "yes";
export default {
'/api/proxy': {
"target": 'http://localhost:3000',
"secure": false,
"bypass": function (req, res, proxyOptions) {
if (req.headers.accept.includes('html')) {
console.log('Skipping proxy for browser request.');
return '/index.html';
}
req.headers['X-Custom-Header'] = 'yes';
}
}
module.exports = PROXY_CONFIG;
}
};
</code-example>
@@ -523,26 +526,27 @@ Use the following content in the JavaScript configuration file.
<code-example format="javascript" language="javascript">
var HttpsProxyAgent = require('https-proxy-agent');
var proxyConfig = [{
import HttpsProxyAgent from 'https-proxy-agent';
const proxyConfig = [{
context: '/api',
target: 'http://your-remote-server.com:3000',
secure: false
}];
function setupForCorporateProxy(proxyConfig) {
var proxyServer = process.env.http_proxy &verbar;&verbar; process.env.HTTP_PROXY;
export default (proxyConfig) => {
const proxyServer = process.env.http_proxy &verbar;&verbar; process.env.HTTP_PROXY;
if (proxyServer) {
var agent = new HttpsProxyAgent(proxyServer);
const agent = new HttpsProxyAgent(proxyServer);
console.log('Using corporate proxy server: ' + proxyServer);
proxyConfig.forEach(function(entry) {
entry.agent = agent;
});
}
return proxyConfig;
}
module.exports = setupForCorporateProxy(proxyConfig);
for (const entry of proxyConfig) {
entry.agent = agent;
}
}
return proxyConfig;
};
</code-example>
@@ -552,4 +556,4 @@ module.exports = setupForCorporateProxy(proxyConfig);
<!-- end links -->
@reviewed 2022-10-24
@reviewed 2023-01-17
+13 -5
View File
@@ -2,7 +2,7 @@
# Find out how much code you're testing
The CLI can run unit tests and create code coverage reports.
The Angular CLI can run unit tests and create code coverage reports.
Code coverage reports show you any parts of your code base that might not be properly tested by your unit tests.
<div class="alert is-helpful">
@@ -19,10 +19,10 @@ ng test --no-watch --code-coverage
</code-example>
When the tests are complete, the command creates a new `/coverage` folder in the project.
When the tests are complete, the command creates a new `/coverage` directory in the project.
Open the `index.html` file to see a report with your source code and code coverage values.
If you want to create code-coverage reports every time you test, set the following option in the CLI configuration file, `angular.json`:
If you want to create code-coverage reports every time you test, set the following option in the Angular CLI configuration file, `angular.json`:
<code-example format="json" language="json">
@@ -63,9 +63,17 @@ coverageReporter: {
</code-example>
<div class="alert is-helpful">
Read more about creating and fine tunning Karma configuration in the [testing guide](guide/testing#configuration).
</div>
The `check` property causes the tool to enforce a minimum of 80% code coverage when the unit tests are run in the project.
Find more information about the different coverage configuration options [here](https://github.com/karma-runner/karma-coverage/blob/master/docs/configuration.md).
Read more on coverage configuration options in the [karma coverage documentation](https://github.com/karma-runner/karma-coverage/blob/master/docs/configuration.md).
<!-- links -->
@@ -73,4 +81,4 @@ Find more information about the different coverage configuration options [here](
<!-- end links -->
@reviewed 2022-02-28
@reviewed 2023-01-17
+5 -64
View File
@@ -77,72 +77,13 @@ The tests run again, the browser refreshes, and the new test results appear.
The Angular CLI takes care of Jasmine and Karma configuration for you. It constructs the full configuration in memory, based on options specified in the `angular.json` file.
If you require to fine-tune Karma, follow the below steps:
If you want to customize Karma, you can create a `karma.conf.js` by running the following command:
1. Create a `karma.conf.js` in the root folder of the project.
<code-example format="shell" language="shell">
<code-example format="javascript" language="javascript" header="karma.conf.js">
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
jasmine: {
// you can add configuration options for Jasmine here
// the possible options are listed at https://jasmine.github.io/api/edge/Configuration.html
// for example, you can disable the random execution with `random: false`
// or set a specific seed with `seed: 4321`
},
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
jasmineHtmlReporter: {
suppressAll: true // removes the duplicated traces
},
coverageReporter: {
dir: require('path').join(__dirname, './coverage/<project-name>'),
subdir: '.',
reporters: [
{ type: 'html' },
{ type: 'text-summary' }
]
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
</code-example>
1. In the `angular.json`, use the [`karmaConfig`](cli/test) option to configure the Karma builder to use the created configuration file.
<code-example format="jsonc" language="jsonc">
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"karmaConfig": "karma.conf.js",
"polyfills": ["zone.js", "zone.js/testing"],
"tsConfig": "src/tsconfig.spec.json",
"styles": ["src/styles.css"]
}
}
</code-example>
ng generate config karma
</code-example>
<div class="alert is-helpful">
@@ -235,4 +176,4 @@ After you've set up your application for testing, you might find the following t
<!-- end links -->
@reviewed 2022-11-02
@reviewed 2023-01-17