docs: integrate cli doc from wiki into main doc (#25776)

PR Close #25776
This commit is contained in:
Judy Bogart 2018-08-31 14:31:17 -07:00 committed by Alex Rickabaugh
parent 7cf5807100
commit f455518d80
6 changed files with 1471 additions and 312 deletions

536
aio/content/guide/build.md Normal file
View File

@ -0,0 +1,536 @@
# Building and serving Angular apps
*intro - here are some topics of interest in the app development cycle*
{@a app-environments}
## Configuring application environments
You can define different named build configurations for your project, such as *stage* and *production*, with different defaults.
Each named build configuration can have defaults for any of the options that apply to the various build targets, such as `build`, `serve`, and `test`. The CLI `build`, `serve`, and `test` commands can then replace files with appropriate versions for your intended target environment.
The following figure shows how a project has multiple build targets, which can be executed using the named configurations that you define.
<figure>
<img src="generated/images/guide/build/build-config-targets.gif" alt="build configurations and targets">
</figure>
### 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.
For example:
```
└──myProject/src/environments/
└──environment.ts
└──environment.prod.ts
└──environment.stage.ts
```
The base file `environment.ts`, contains the default environment settings. For example:
<code-example language="none" class="code-shell">
export const environment = {
production: false
};
</code-example>
The `build` command uses this as the build target when no environment is specified.
You can add further variables, either as additional properties on the environment object, or as separate objects.
For example, the following adds a default for a variable to the default environment:
```
export const environment = {
production: false,
apiUrl: 'http://my-api-url'
};
```
You can add target-specific configuration files, such as `environment.prod.ts`.
The following sets content sets default values for the production build target:
```
export const environment = {
production: true
apiUrl: 'http://my-prod-url'
};
```
### Using environment-specific variables in your app
The following application structure configures build targets for production and staging environments:
```
└── src
└── app
├── app.component.html
└── app.component.ts
└── environments
├── environment.prod.ts
├── environment.staging.ts
└── environment.ts
```
To use the environment configurations you have defined, your components must import the original environments file:
```
import { environment } from './../environments/environment';
```
This ensures that the build and serve commands can find the configurations for specific build targets.
The following code in the component file (`app.component.ts`) uses an environment variable defined in the configuration files.
```
import { Component } from '@angular/core';
import { environment } from './../environments/environment';
@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
}
title = 'app works!';
}
```
{@a file-replacement}
## Configure target-specific file replacements
The main CLI configuration file, `angular.json`, contains a `fileReplacements` section in the configuration for each build target, which allows you to replace any file with a target-specific version of that file.
This is useful for including target-specific code or variables in a build that targets a specific environment, such as production or staging.
By default no files are replaced.
You can add file replacements for specific build targets.
For example:
```
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
...
```
This means that when you build your production configuration (using `ng build --prod` or `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`.
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`:
```
"configurations": {
"production": { ... },
"staging": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.staging.ts"
}
]
}
}
```
You can add more configuration options to this target environment as well.
Any option that your build supports can be overridden in a build target configuration.
To build using the staging configuration, run `ng build --configuration=staging`.
You can also configure the `serve` command to use the targeted build configuration if you add it to the "serve:configurations" section of `angular.json`:
```
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "your-project-name:build"
},
"configurations": {
"production": {
"browserTarget": "your-project-name:build:production"
},
"staging": {
"browserTarget": "your-project-name:build:staging"
}
}
},
```
{@a size-budgets}
## Configure size budgets
As applications grow in functionality, they also grow in size.
The CLI allows you to set size thresholds in your configuration to ensure that parts of your application stay within size boundaries that you define.
Define your size boundaries in the CLI configuration file, `angular.json`, in a `budgets` section for each [configured environment](#app-environments).
```
{
...
"configurations": {
"production": {
...
budgets: []
}
}
}
```
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:
* 123 or 123b: Size in bytes
* 123kb: Size in kilobytes
* 123mb: Size in megabytes
* 12%: Percentage of size relative to baseline. (Not valid for baseline values.)
When you configure a budget, the build system warns or reports and error when a given part of the app reaches or exceeds a boundary size that you set.
Each budget entry is a JSON object with the following properties:
<table>
<tr>
<th>Property</th>
<th>Value</th>
</tr>
<tr>
<td>type</td>
<td>The type of budget. One of:
* bundle - The size of a specific bundle.
* initial - The initial size of the app.
* allScript - The size of all scripts.
* all - The size of the entire app.
* anyScript - The size of any one script.
* any - The size of any file.
</td>
</tr>
<tr>
<td>name</td>
<td>
The name of the bundle (for `type=bundle`).
</td>
</tr>
<tr>
<td>baseline</td>
<td>An absolute baseline size for percentage values. </td>
</tr>
<tr>
<td>maximumWarning</td>
<td>Warns when a size exceeds this threshold percentage of the baseline.</td>
</tr>
<tr>
<td>maximumError</td>
<td>Reports an error when the size exceeds this threshold percentage of the baseline.</td>
</tr>
<tr>
<td>minimumWarning</td>
<td>Warns when the size reaches this threshold percentage of the baseline.</td>
</tr>
<tr>
<td>minimumError</td>
<td>Reports an error when the size reaches this threshold percentage of the baseline.</td>
</tr>
<tr>
<td>warning</td>
<td>Warns when the size ??reaches or exceeds?? this threshold percentage of the baseline.</td>
</tr>
<tr>
<td>error</td>
<td>Reports an error when the size ??reaches or exceeds?? this threshold percentage of the baseline.</td>
</tr>
</table>
{@a assets}
## Adding project assets
You can configure your project with a set of assets, such as images, to copy directly into the build for a particular build target.
Each build target section of the CLI configuration file, `angular.json`, has an `assets` section that lists files or folders you want to copy into the build for that target.
By default, the `src/assets/` folder and `src/favicon.ico` are copied into a build.
```
"assets": [
"src/assets",
"src/favicon.ico"
]
```
You can edit the assets configuration to extend it for assets outside your project.
For example, the following invokes the [node-glob pattern matcher](https://github.com/isaacs/node-glob) using input from a given base folder.
It sends output to a folder that is relative to `outDir`, a configuration value that defaults to `dist/`*project-name*).
The result in this cased is the same as for the default assets configuration.
```
"assets": [
{ "glob": "**/*", "input": "src/assets/", "output": "/assets/" },
{ "glob": "favicon.ico", "input": "/src", "output": "/" },
]
```
You can use this extended configuration to copy assets from outside your project.
For instance, you can copy assets from a node package with the following value:
```
"assets": [
{ "glob": "**/*", "input": "./node_modules/some-package/images", "output": "/some-package/" },
]
```
This makes the contents of `node_modules/some-package/images/` available in the output folder `dist/some-package/`.
<div class="alert is-critical">
For reasons of security, the CLI never writes files outside of the project output path.
</div>
{@a browser-compat}
## Configuring browser compatibility
The CLI uses [Autoprefixer](https://github.com/postcss/autoprefixer) to ensure compatibility with different browser and browser versions.
You may find it necessary to target specific browsers or exclude certain browser versions from your build.
Internally, Autoprefixer relies on a library called [Browserslist(https://github.com/ai/browserslist)] to figure out which browsers to support with prefixing.
Browserlist looks for configuration options in a `browserlist` property of the package configuration file, or in a configuration file named `.browserslistrc`.
Autoprefixer looks for the Browserlist configuration when it prefixes your CSS.
* You can tell Autoprefixer what browsers to target by adding a browserslist property to the package configuration file, `package.json`:
```
"browserslist": [
"> 1%",
"last 2 versions"
]
```
* Alternatively, you can add a new file, `.browserslistrc`, to the project directory, that specifies browsers you want to support:
```
### Supported Browsers
> 1%
last 2 versions
```
See the [browserslist repo](https://github.com/ai/browserslist) for more examples of how to target specific browsers and versions.
<div class="alert is-helpful">>
Backward compatibility
If you want to produce a progressive web app and are using [Lighthouse](https://developers.google.com/web/tools/lighthouse/) to grade the project, add the following browserslist entry to your `package.json` file, in order to eliminate the [old flexbox](https://developers.google.com/web/tools/lighthouse/audits/old-flexbox) prefixes:
```
"browserslist": [
"last 2 versions",
"not ie <= 10",
"not ie_mob <= 10"
]
```
</div>
{@a proxy}
## Proxying to a backend server
You can use the [proxying support](https://webpack.js.org/configuration/dev-server/#devserver-proxy) in the `webpack` dev server to divert certain URLs to a backend server, by passing a file to the `--proxy-config` build option.
For example, to divert all calls for http://localhost:4200/api to a server running on http://localhost:3000/api, take the following steps.
1. Create a file `proxy.conf.json` in the projects `src/` folder, next to `package.json`.
1. Add the following content to the new proxy file:
```
{
"/api": {
"target": "http://localhost:3000",
"secure": false
}
}
```
1. In the CLI configuration file, `angular.json`, add the `proxyConfig` option to the `serve` target:
```
...
"architect": {
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "your-application-name:build",
"proxyConfig": "src/proxy.conf.json"
},
...
```
1. To run the dev server with this proxy configuration, call `ng serve`.
You can edit the proxy configuration file to add configuration options; some examples are given below.
For a description of all options, see [webpack DevServer documentation](https://webpack.js.org/configuration/dev-server/#devserver-proxy).
Note that if you edit the proxy configuration file, you must relaunch the `ng serve` process to make your changes effective.
### Rewrite the URL path
The `pathRewrite` proxy configuration option lets you rewrite the URL path at run time.
For example, you can specify the following `pathRewrite` value to the proxy configuration to remove "api" from the end of a path.
```
{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"pathRewrite": {
"^/api": ""
}
}
}
```
If you need to access a backend that is not on `localhost`, set the `changeOrigin` option as well. For example:
```
{
"/api": {
"target": "http://npmjs.org",
"secure": false,
"pathRewrite": {
"^/api": ""
},
"changeOrigin": true
}
}
```
To help determine whether your proxy is working as intended, set the `logLevel` option. For example:
```
{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"pathRewrite": {
"^/api": ""
},
"logLevel": "debug"
}
}
```
Proxy log levels are `info` (the default), `debug`, `warn`, `error`, and `silent`.
### Proxy multiple entries
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.
```
const PROXY_CONFIG = [
{
context: [
"/my",
"/many",
"/endpoints",
"/i",
"/need",
"/to",
"/proxy"
],
target: "http://localhost:3000",
secure: false
}
]
module.exports = PROXY_CONFIG;
```
In the CLI configuration file, `angular.json`, point to the JavaScript proxy configuration file:
```
...
"architect": {
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "your-application-name:build",
"proxyConfig": "src/proxy.conf.js"
},
...
```
### Bypass the proxy
If you need to optionally bypass the proxy, or dynamically change the request before it's sent, add the bypass option, as shown in this JavaScript example.
```
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";
}
}
}
module.exports = PROXY_CONFIG;
```
### Using corporate proxy
If you work behind a corporate proxy, the cannot directly proxy calls to any URL outside your local network.
In this case, you can configure the backend proxy to redirect calls through your corporate proxy using an agent:
<code-example language="none" class="code-shell">
npm install --save-dev https-proxy-agent
</code-example>
When you define an environment variable `http_proxy` or `HTTP_PROXY`, an agent is automatically added to pass calls through your corporate proxy when running `npm start`.
Use the following content in the JavaScript configuration file.
```
var HttpsProxyAgent = require('https-proxy-agent');
var proxyConfig = [{
context: '/api',
target: 'http://your-remote-server.com:3000',
secure: false
}];
function setupForCorporateProxy(proxyConfig) {
var proxyServer = process.env.http_proxy || process.env.HTTP_PROXY;
if (proxyServer) {
var agent = new HttpsProxyAgent(proxyServer);
console.log('Using corporate proxy server: ' + proxyServer);
proxyConfig.forEach(function(entry) {
entry.agent = agent;
});
}
return proxyConfig;
}
module.exports = setupForCorporateProxy(proxyConfig);
```

View File

@ -1,6 +1,7 @@
# Deployment
This page describes techniques for deploying your Angular application to a remote server.
When you are ready to deploy your Angular application to a remote server, you have various options for
deployment. You may need to configure
{@a dev-deploy}
{@a copy-files}
@ -18,27 +19,214 @@ For the simplest deployment, build for development and copy the output directory
2. Copy _everything_ within the output folder (`dist/` by default) to a folder on the server.
3. If you copy the files into a server _sub-folder_, append the build flag, `--base-href` and set the `<base href>` appropriately.<br><br>
For example, if the `index.html` is on the server at `/my/app/index.html`, set the _base href_ to
`<base href="/my/app/">` like this.
<code-example language="none" class="code-shell">
ng build --base-href=/my/app/
</code-example>
You'll see that the `<base href>` is set properly in the generated `dist/index.html`.<br><br>
If you copy to the server's root directory, omit this step and leave the `<base href>` alone.<br><br>
Learn more about the role of `<base href>` [below](guide/deployment#base-tag).
4. Configure the server to redirect requests for missing files to `index.html`.
3. Configure the server to redirect requests for missing files to `index.html`.
Learn more about server-side redirects [below](guide/deployment#fallback).
This is _not_ a production deployment. It's not optimized and it won't be fast for users.
It might be good enough for sharing your progress and ideas internally with managers, teammates, and other stakeholders.
It might be good enough for sharing your progress and ideas internally with managers, teammates, and other stakeholders. For the next steps in deployment, see [Optimize for production](#optimize).
{@a deploy-to-github}
## Deploy to GitHub pages
Another simple way to deploy your Angular app is to use [GitHub Pages](https://help.github.com/articles/what-is-github-pages/).
1. You will need to [create a GitHub account](https://github.com/join) if you don't have one, then [create a repository](https://help.github.com/articles/create-a-repo/) for your project.
Make a note of the user name and project name in GitHub.
1. Build your project using Github project name, with the following CLI command:
<code-example language="none" class="code-shell">
ng build --prod --output-path docs --base-href <project_name>
</code-example>
1. When the build is complete, make a copy of `docs/index.html` and name it `docs/404.html`.
1. Commit your changes and push.
1. On the GitHub project page, configure it to [publish from the docs folder](https://help.github.com/articles/configuring-a-publishing-source-for-github-pages/#publishing-your-github-pages-site-from-a-docs-folder-on-your-master-branch).
You can see your deployed page at `https://<user_name>.github.io/<project_name>/`.
<div class="alert-is-helpful>
Check out [angular-cli-ghpages](https://github.com/angular-buch/angular-cli-ghpages), a full featured package that does all this for you and has extra functionality.
</div>
<hr>
{@a server-configuration}
## Server configuration
This section covers changes you may have make to the server or to files deployed to the server.
{@a fallback}
### Routed apps must fallback to `index.html`
Angular apps are perfect candidates for serving with a simple static HTML server.
You don't need a server-side engine to dynamically compose application pages because
Angular does that on the client-side.
If the app uses the Angular router, you must configure the server
to return the application's host page (`index.html`) when asked for a file that it does not have.
{@a deep-link}
A routed application should support "deep links".
A _deep link_ is a URL that specifies a path to a component inside the app.
For example, `http://www.mysite.com/heroes/42` is a _deep link_ to the hero detail page
that displays the hero with `id: 42`.
There is no issue when the user navigates to that URL from within a running client.
The Angular router interprets the URL and routes to that page and hero.
But clicking a link in an email, entering it in the browser address bar,
or merely refreshing the browser while on the hero detail page &mdash;
all of these actions are handled by the browser itself, _outside_ the running application.
The browser makes a direct request to the server for that URL, bypassing the router.
A static server routinely returns `index.html` when it receives a request for `http://www.mysite.com/`.
But it rejects `http://www.mysite.com/heroes/42` and returns a `404 - Not Found` error *unless* it is
configured to return `index.html` instead.
#### Fallback configuration examples
There is no single configuration that works for every server.
The following sections describe configurations for some of the most popular servers.
The list is by no means exhaustive, but should provide you with a good starting point.
#### Development servers
During development, the `ng serve` command lets you run your app in a local browser.
The CLI recompiles the application each time you save a file,
and reloads the browser with the newly compiled application.
The app is hosted in local memory and served on `http://localhost:4200/`, using [webpack-dev-server](https://webpack.js.org/guides/development/#webpack-dev-server).
{@a serve-from-disk}
Later in development, you might want a closer approximation of how your app will behave when deployed.
You can output your distribution folder (`dist`) to disk, but you need to install a different web server.
Try installing [lite-server](https://github.com/johnpapa/lite-server); like `webpack-dev-server`, it can automatically reload your browser when you write new files.
To get the live-reload experience, you will need to run two terminals.
The first runs the build in a watch mode and compiles the application to the `dist` folder.
The second runs the web server against the `dist` folder.
The combination of these two processes provides the same behavior as `ng serve`.
1. Start the build in terminal A:
<code-example language="none" class="code-shell">
ng build --watch
</code-example>
1. Start the web server in terminal B:
<code-example language="none" class="code-shell">
lite-server --baseDir="dist"
</code-example>
The default browser opens to the appropriate URL.
* [Lite-Server](https://github.com/johnpapa/lite-server): the default dev server installed with the
[Quickstart repo](https://github.com/angular/quickstart) is pre-configured to fallback to `index.html`.
* [Webpack-Dev-Server](https://github.com/webpack/webpack-dev-server): setup the
`historyApiFallback` entry in the dev server options as follows:
<code-example>
historyApiFallback: {
disableDotRule: true,
htmlAcceptHeaders: ['text/html', 'application/xhtml+xml']
}
</code-example>
#### Production servers
* [Apache](https://httpd.apache.org/): add a
[rewrite rule](http://httpd.apache.org/docs/current/mod/mod_rewrite.html) to the `.htaccess` file as shown
(https://ngmilk.rocks/2015/03/09/angularjs-html5-mode-or-pretty-urls-on-apache-using-htaccess/):
<code-example format=".">
RewriteEngine On
&#35 If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
&#35 If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html
</code-example>
* [Nginx](http://nginx.org/): use `try_files`, as described in
[Front Controller Pattern Web Apps](https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#front-controller-pattern-web-apps),
modified to serve `index.html`:
<code-example format=".">
try_files $uri $uri/ /index.html;
</code-example>
* [IIS](https://www.iis.net/): add a rewrite rule to `web.config`, similar to the one shown
[here](http://stackoverflow.com/a/26152011/2116927):
<code-example format='.'>
&lt;system.webServer&gt;
&lt;rewrite&gt;
&lt;rules&gt;
&lt;rule name="Angular Routes" stopProcessing="true"&gt;
&lt;match url=".*" /&gt;
&lt;conditions logicalGrouping="MatchAll"&gt;
&lt;add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /&gt;
&lt;add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /&gt;
&lt;/conditions&gt;
&lt;action type="Rewrite" url="/index.html" /&gt;
&lt;/rule&gt;
&lt;/rules&gt;
&lt;/rewrite&gt;
&lt;/system.webServer&gt;
</code-example>
* [GitHub Pages](https://pages.github.com/): you can't
[directly configure](https://github.com/isaacs/github/issues/408)
the GitHub Pages server, but you can add a 404 page.
Copy `index.html` into `404.html`.
It will still be served as the 404 response, but the browser will process that page and load the app properly.
It's also a good idea to
[serve from `docs/` on master](https://help.github.com/articles/configuring-a-publishing-source-for-github-pages/#publishing-your-github-pages-site-from-a-docs-folder-on-your-master-branch)
and to
[create a `.nojekyll` file](https://www.bennadel.com/blog/3181-including-node-modules-and-vendors-folders-in-your-github-pages-site.htm)
* [Firebase hosting](https://firebase.google.com/docs/hosting/): add a
[rewrite rule](https://firebase.google.com/docs/hosting/url-redirects-rewrites#section-rewrites).
<code-example format=".">
"rewrites": [ {
"source": "**",
"destination": "/index.html"
} ]
</code-example>
{@a cors}
### Requesting services from a different server (CORS)
Angular developers may encounter a
<a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing" title="Cross-origin resource sharing">
<i>cross-origin resource sharing</i></a> error when making a service request (typically a data service request)
to a server other than the application's own host server.
Browsers forbid such requests unless the server permits them explicitly.
There isn't anything the client application can do about these errors.
The server must be configured to accept the application's requests.
Read about how to enable CORS for specific servers at
<a href="http://enable-cors.org/server.html" title="Enabling CORS server">enable-cors.org</a>.
<hr>
{@a optimize}
@ -65,14 +253,8 @@ The `--prod` _meta-flag_ engages the following optimization features.
The remaining [copy deployment steps](#copy-files) are the same as before.
You may further reduce bundle sizes by adding the `build-optimizer` flag.
<code-example language="none" class="code-shell">
ng build --prod --build-optimizer
</code-example>
See the [CLI Documentation](https://github.com/angular/angular-cli/wiki/build)
for details about available build options and what they do.
See [Building and serving Angular apps](guide/build)
for more about about CLI build options and what they do.
{@a enable-prod-mode}
@ -102,22 +284,24 @@ Configure the Angular Router to defer loading of all other modules (and their as
or by [_lazy loading_](guide/router#asynchronous-routing "Lazy loading")
them on demand.
#### Don't eagerly import something from a lazy loaded module
<div class="alert-is-helpful>
It's a common mistake.
You've arranged to lazy load a module.
But you unintentionally import it, with a JavaScript `import` statement,
in a file that's eagerly loaded when the app starts, a file such as the root `AppModule`.
#### Don't eagerly import something from a lazy-loaded module
If you mean to lazy-load a module, be careful not import it
in a file that's eagerly loaded when the app starts (such as the root `AppModule`).
If you do that, the module will be loaded immediately.
The bundling configuration must take lazy loading into consideration.
Because lazy loaded modules aren't imported in JavaScript (as just noted), bundlers exclude them by default.
Bundlers don't know about the router configuration and won't create separate bundles for lazy loaded modules.
You have to create these bundles manually.
Because lazy-loaded modules aren't imported in JavaScript, bundlers exclude them by default.
Bundlers don't know about the router configuration and can't create separate bundles for lazy-loaded modules.
You would have to create these bundles manually.
The CLI runs the
[Angular Ahead-of-Time Webpack Plugin](https://github.com/angular/angular-cli/tree/master/packages/%40ngtools/webpack)
which automatically recognizes lazy loaded `NgModules` and creates separate bundles for them.
which automatically recognizes lazy-loaded `NgModules` and creates separate bundles for them.
</div>
{@a measure}
@ -203,17 +387,12 @@ the subfolder is `my/app/` and you should add `<base href="/my/app/">` to the se
When the `base` tag is mis-configured, the app fails to load and the browser console displays `404 - Not Found` errors
for the missing files. Look at where it _tried_ to find those files and adjust the base tag appropriately.
## _build_ vs. _serve_
## Building and serving for deployment
You'll probably prefer `ng build` for deployments.
When you are designing and developing applications, you typically use `ng serve` to build your app for fast, local, iterative development.
When you are ready to deploy, however, you must use the `ng build` command to build the app and deploy the build artifacts elsewhere.
The **ng build** command is intended for building the app and deploying the build artifacts elsewhere.
The **ng serve** command is intended for fast, local, iterative development.
Both `ng build` and `ng serve` **clear the output folder** before they build the project.
The `ng build` command writes generated build artifacts to the output folder.
The `ng serve` command does not.
It serves build artifacts from memory instead for a faster development experience.
Both `ng build` and `ng serve` clear the output folder before they build the project, but only the `build` command writes the generated build artifacts to the output folder.
<div class="alert is-helpful">
@ -222,160 +401,13 @@ To output to a different folder, change the `outputPath` in `angular.json`.
</div>
The `ng serve` command builds, watches, and serves the application from a local CLI development server.
The`serve` command builds, watches, and serves the application from local memory, using a local development server.
When you have deployed your app to another server, however, you might still want to serve the app so that you can continue to see changes that you make in it.
You can do this by adding the `--watch` option to the `build` command.
The `ng build` command generates output files just once and does not serve them.
The `ng build --watch` command will regenerate output files when source files change.
This `--watch` flag is useful if you're building during development and
are automatically re-deploying changes to another server.
```
ng build --watch
```
Like the `serve` command, this regenerates output files when source files change.
See the [CLI `build` topic](https://github.com/angular/angular-cli/wiki/build) for more details and options.
<hr>
{@a server-configuration}
## Server configuration
This section covers changes you may have make to the server or to files deployed to the server.
{@a fallback}
### Routed apps must fallback to `index.html`
Angular apps are perfect candidates for serving with a simple static HTML server.
You don't need a server-side engine to dynamically compose application pages because
Angular does that on the client-side.
If the app uses the Angular router, you must configure the server
to return the application's host page (`index.html`) when asked for a file that it does not have.
{@a deep-link}
A routed application should support "deep links".
A _deep link_ is a URL that specifies a path to a component inside the app.
For example, `http://www.mysite.com/heroes/42` is a _deep link_ to the hero detail page
that displays the hero with `id: 42`.
There is no issue when the user navigates to that URL from within a running client.
The Angular router interprets the URL and routes to that page and hero.
But clicking a link in an email, entering it in the browser address bar,
or merely refreshing the browser while on the hero detail page &mdash;
all of these actions are handled by the browser itself, _outside_ the running application.
The browser makes a direct request to the server for that URL, bypassing the router.
A static server routinely returns `index.html` when it receives a request for `http://www.mysite.com/`.
But it rejects `http://www.mysite.com/heroes/42` and returns a `404 - Not Found` error *unless* it is
configured to return `index.html` instead.
#### Fallback configuration examples
There is no single configuration that works for every server.
The following sections describe configurations for some of the most popular servers.
The list is by no means exhaustive, but should provide you with a good starting point.
#### Development servers
* [Lite-Server](https://github.com/johnpapa/lite-server): the default dev server installed with the
[Quickstart repo](https://github.com/angular/quickstart) is pre-configured to fallback to `index.html`.
* [Webpack-Dev-Server](https://github.com/webpack/webpack-dev-server): setup the
`historyApiFallback` entry in the dev server options as follows:
<code-example>
historyApiFallback: {
disableDotRule: true,
htmlAcceptHeaders: ['text/html', 'application/xhtml+xml']
}
</code-example>
#### Production servers
* [Apache](https://httpd.apache.org/): add a
[rewrite rule](http://httpd.apache.org/docs/current/mod/mod_rewrite.html) to the `.htaccess` file as shown
(https://ngmilk.rocks/2015/03/09/angularjs-html5-mode-or-pretty-urls-on-apache-using-htaccess/):
<code-example format=".">
RewriteEngine On
&#35 If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
&#35 If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html
</code-example>
* [NGinx](http://nginx.org/): use `try_files`, as described in
[Front Controller Pattern Web Apps](https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#front-controller-pattern-web-apps),
modified to serve `index.html`:
<code-example format=".">
try_files $uri $uri/ /index.html;
</code-example>
* [IIS](https://www.iis.net/): add a rewrite rule to `web.config`, similar to the one shown
[here](http://stackoverflow.com/a/26152011/2116927):
<code-example format='.'>
&lt;system.webServer&gt;
&lt;rewrite&gt;
&lt;rules&gt;
&lt;rule name="Angular Routes" stopProcessing="true"&gt;
&lt;match url=".*" /&gt;
&lt;conditions logicalGrouping="MatchAll"&gt;
&lt;add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /&gt;
&lt;add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /&gt;
&lt;/conditions&gt;
&lt;action type="Rewrite" url="/index.html" /&gt;
&lt;/rule&gt;
&lt;/rules&gt;
&lt;/rewrite&gt;
&lt;/system.webServer&gt;
</code-example>
* [GitHub Pages](https://pages.github.com/): you can't
[directly configure](https://github.com/isaacs/github/issues/408)
the GitHub Pages server, but you can add a 404 page.
Copy `index.html` into `404.html`.
It will still be served as the 404 response, but the browser will process that page and load the app properly.
It's also a good idea to
[serve from `docs/` on master](https://help.github.com/articles/configuring-a-publishing-source-for-github-pages/#publishing-your-github-pages-site-from-a-docs-folder-on-your-master-branch)
and to
[create a `.nojekyll` file](https://www.bennadel.com/blog/3181-including-node-modules-and-vendors-folders-in-your-github-pages-site.htm)
* [Firebase hosting](https://firebase.google.com/docs/hosting/): add a
[rewrite rule](https://firebase.google.com/docs/hosting/url-redirects-rewrites#section-rewrites).
<code-example format=".">
"rewrites": [ {
"source": "**",
"destination": "/index.html"
} ]
</code-example>
{@a cors}
### Requesting services from a different server (CORS)
Angular developers may encounter a
<a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing" title="Cross-origin resource sharing">
<i>cross-origin resource sharing</i></a> error when making a service request (typically a data service request)
to a server other than the application's own host server.
Browsers forbid such requests unless the server permits them explicitly.
There isn't anything the client application can do about these errors.
The server must be configured to accept the application's requests.
Read about how to enable CORS for specific servers at
<a href="http://enable-cors.org/server.html" title="Enabling CORS server">enable-cors.org</a>.
For complete details of the CLI commands and configuration options, see the *CLI Reference (link TBD)*.

View File

@ -0,0 +1,382 @@
# Workspace and project file structure
An Angular CLI project is the foundation for both quick experiments and enterprise solutions. The CLI command `ng new` creates an Angular workspace in your file system that is the root for new projects, which can be apps and libraries.
## Workspaces and project files
Angular 6 introduced the [workspace](guide/glossary#workspace) directory structure for Angular [projects](guide/glossary#project). A project can be a standalone *application* or a *library*, and a workspace can contain multiple applications, as well as libraries that can be used in any of the apps.
The CLI command `ng new my-workspace` creates a workspace folder and generates a new app skeleton in an `app` folder within that workspace.
Within the `app/` folder, a `src/` subfolder contains the logic, data, and assets.
A newly generated `app/` folder contains the source files for a root module, with a root component and template.
The `app/` folder also contains project-specific configuration files, end-to-end tests, and the Angular system modules.
```
my-workspace/
app/
e2e/
src/
node_modules/
src/
```
When this workspace file structure is in place, you can use the `ng generate` command on the command line to add functionality and data to the initial app.
<div class="alert-is-helpful>
Besides using the CLI on the command line, You can also use an interactive development environment like [Angular Console](https://angular.console.com), or manipulate files directly in the app's source folder and configuration files.
</div>
{@a global-config}
## Global workspace configuration
A workspace can contain additional apps and libraries, each with its own root folder under `projects/`.
```
my-workspace/
app/
projects/
my-app/
helpful-library/
my-other-app/
angular.json
```
At the top level of the workspace, the CLI configuration file, `angular.json`, let you set defaults for all projects in the workspace. You can configure a workspace, for example, such that all projects in it have global access to libraries, scripts, and CSS styles. (For more in this, see [Configuring global access](#global-access).)
You can also use `ng generate app` to create new Angular apps in the workspace, and use the `ng add` command to add libraries.
If you add libraries or generate more apps within a workspace, a `projects/` folder is created to contain the new libraries or apps.
Additional apps and library subfolders have the same file structure as the initial app.
All of the projects within a workspace share a CLI configuration context, controlled by the `angular.json` configuration file at the root level of the workspace.
| GLOBAL CONFIG FILES | PURPOSE |
| :------------- | :------------------------------------------|
| `angular.json` | Sets defaults for the CLI and configuration options for build, serve, and test tools that the CLI uses, such as [Karma](https://karma-runner.github.io/) and [Protractor](http://www.protractortest.org/). For complete details, see *CLI Reference (link TBD)*. |
## App source folder
The app-root source folder contains your app's logic and data. Angular components, templates, styles, images, and anything else your app needs go here. Files outside of the source folder support testing and building your app.
```
src/
app/
app.component.css
app.component.html
app.component.spec.ts
app.component.ts
app.module.ts
assets/...
favicon.ico
index.html
main.ts
test.ts
```
| APP SOURCE FILES | PURPOSE |
| :----------------------------- | :------------------------------------------|
| `app/app.component.ts` | Defines the logic for the app's root component, named AppComponent. The view associated with this root component becomes the root of the [view hierarchy](guide/glossary#view-hierarchy) as you add components and services to your app. |
| `app/app.component.html` | Defines the HTML template associated with the root AppComponent. |
| `app/app.component.css` | Defines the base CSS stylesheet for the root AppComponent. |
| `app/app.component.spec.ts` | Defines a unit test for the root AppComponent. |
| `app/app.module.ts` | Defines the root module, named AppModule, that tells Angular how to assemble the application. Initially declares only the AppComponent. As you add more components to the app, they must be declared here. |
| `assets/*` | Contains image files and other asset files to be copied as-is when you build your application. |
| PROJECT-LEVEL FILES | PURPOSE |
| :------------------------ | :------------------------------------------|
| `favicon.ico` | An icon to use for this app in the bookmark bar. |
| `index.html` | The main HTML page that is served when someone visits your site. The CLI automatically adds all JavaScript and CSS files when building your app, so you typically don't need to add any `<script>` or` <link>` tags here manually. |
| `main.ts` | The main entry point for your app. Compiles the application with the [JIT compiler](https://angular.io/guide/glossary#jit) and bootstraps the application's root module (AppModule) to run in the browser. You can also use the [AOT compiler](https://angular.io/guide/aot-compiler) without changing any code by appending the `--aot` flag to the CLI `build` and `serve` commands. |
| `test.ts` | The main entry point for your unit tests, with some Angular-specific configuration. You don't typically need to edit this file. |
## App support file structure
Additional files in a project's root folder help you build, test, maintain, document, and deploy the app. These files go in the app root folder next to `src/`.
```
workspace_root/
my-app/
e2e/
src/
app.e2e-spec.ts
app.po.ts
tsconfig.e2e.json
protractor.conf.js
node_modules/...
src/...
```
| FOLDERS | PURPOSE |
| :---------------- | :-------------------------------------------- |
| `e2e/` | This folder contains end-to-end tests for the app. This is a separate app that tests your main app. The folder and its contents are generated automatically when you create a new app with the CLI `new` or `generate` command. |
| `node_modules/` | Node.js creates this folder and puts all third party modules listed in `package.json` in it. *when? doesn't ng new create it?* |
### Project-level configuration
Each project uses the CLI configuration at the workspace root-level `angular.json` file.
Additional project-specific configuration files are found at the project root level of each app or library.
```
my-workspace/
app/
.editorconfig
.gitignore
package.json
README.md
tsconfig.json
tsconfig.test.json
tslint.json
projects/
helpful-library/
my-other-app/
.editorconfig
.gitignore
package.json
README.md
tsconfig.json
tsconfig.test.json
tslint.json
angular.json
```
| CONFIGURATION FILES | PURPOSE |
| :------------------ | :-------------------------------------------- |
| `.editorconfig` | Simple configuration for your editor to make sure everyone who uses your project has the same basic configuration. Supported by most editors. See http://editorconfig.org for more information. |
| `.gitignore` | Git configuration to make sure autogenerated files are not committed to source control. |
| `package.json` | Configures the `npm` package manager, listing the third party packages your project uses. You can also add your own custom scripts here. |
| `README.md` | Basic documentation for your project, pre-filled with CLI command information. We recommend that you keep this updated so that anyone checking out the repo can build your app. |
| `tsconfig.json` | TypeScript compiler configuration, that an IDE such as [Visual Studio Code](https://code.visualstudio.com/) uses to give you helpful tooling. |
| `tslint.json` | Linting configuration for [TSLint](https://palantir.github.io/tslint/) together with [Codelyzer](http://codelyzer.com/), used when running the CLI `lint` command. Linting helps keep your code style consistent. |
{@a global-access}
## Configuring global access
The CLI configuration scope is global for a workspace.
You can make scripts, libraries, and styles available to all projects in the workspace by setting options in the `angular.json` file in the root workspace folder.
### Adding global scripts
You can configure your project to add JavaScript files to the global scope.
This is especially useful for legacy libraries or analytic snippets.
In the CLI configuration file, `angular.json`, add the associated script files to the `scripts` array.
The scripts are loaded exactly as if you had added them in a `<script>` tag inside `index.html`.
For example:
```
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"scripts": [
"src/global-script.js",
],
```
You can also rename the output from a script and lazy load it by using the object format in the "scripts" entry.
For example:
```
"scripts": [
"src/global-script.js",
{ "input": "src/lazy-script.js", "lazy": true },
{ "input": "src/pre-rename-script.js", "bundleName": "renamed-script" },
],
```
If you need to add scripts for unit tests, specify them the same way in the "test" target.
{@a add-lib}
### Adding a global library
Some JavaScript libraries need to be added to the global scope and loaded as if they were in a script tag.
Configure the CLI to do this using the "scripts" and "styles" options of the build target in the CLI configuration file, `angular.json`.
For example, to use the [Bootstrap 4](https://getbootstrap.com/docs/4.0/getting-started/introduction/)
library, first install the library and its dependencies using the `npm` package manager:
```
npm install jquery --save
npm install popper.js --save
npm install bootstrap --save
```
In the `angular.json` configuration file, add the associated script files to the "scripts" array:
```
"scripts": [
"node_modules/jquery/dist/jquery.slim.js",
"node_modules/popper.js/dist/umd/popper.js",
"node_modules/bootstrap/dist/js/bootstrap.js"
],
```
Add the Bootstrap CSS file to the "styles" array:
```
"styles": [
"node_modules/bootstrap/dist/css/bootstrap.css",
"src/styles.css"
],
```
Run or restart `ng serve` to see Bootstrap 4 working in your app.
#### Using global libraries inside your app
Once you import a library using the "scripts" array in the configuration file,
you should *not* import it using an `import` statement in your TypeScript code
(such as `import * as $ from 'jquery';`).
If you do, you'll end up with two different copies of the library:
one imported as a global library, and one imported as a module.
This is especially bad for libraries with plugins, like JQuery,
because each copy will have different plugins.
Instead, download typings for your library (`npm install @types/jquery`) and follow the installation steps
given above in [Adding a global library](#add-lib).
This gives you access to the global variables exposed by that library.
{@a define-types}
#### Defining typings for global libraries
If the global library you need to use does not have global typings,
you can declare them manually as `any` in `src/typings.d.ts`. For example:
```
declare var libraryName: any;
```
Some scripts extend other libraries; for instance with JQuery plugins:
```
$('.test').myPlugin();
```
In this case, the installed `@types/jquery` doesn't include `myPlugin`,
so you need to add an *interface* in `src/typings.d.ts`.
For example:
```
interface JQuery {
myPlugin(options?: any): any;
}
```
If you fail to add the interface for the script-defined extension, your IDE shows an error:
```
[TS][Error] Property 'myPlugin' does not exist on type 'JQuery'
```
### Adding global styles and style preprocessors
Angular CLI supports CSS imports and all major CSS preprocessors:
* [Sass/Scss](http://sass-lang.com/)
* [Less](http://lesscss.org/)
* [Stylus](http://stylus-lang.com/)
Angular assumes CSS styles by default, but when you create a project with the
CLI `new` command, you can specify the `--style` option to use SASS or STYL styles.
```
> ng new sassyproject --style=sass
> ng new scss-project --style=scss
> ng new less-project --style=less
> ng new styl-project --style=styl
```
You can also set the default style for an existing project by configuring `@schematics/angular`,
the default schematic for the Angular CLI:
```
> ng config schematics.@schematics/angular:component.styleext scss
```
#### Style configuration
By default, the `styles.css` configuration file lists CSS files that supply global styles for a project.
If you are using another style type, there is a similar configuration file for global style files of that type,
with the extension for that style type, such as `styles.sass`.
You can add more global styles by configuring the build options in the `angular.json` configuration file.
List the style files in the "styles" section in your project's "build" target
The files are loaded exactly as if you had added them in a `<link>` tag inside `index.html`.
```
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"styles": [
"src/styles.css",
"src/more-styles.css",
],
...
```
If you need the styles in your unit tests, add them to the "styles" option in the "test" target configuration as well.
You can specify styles in an object format to rename the output and lazy load it:
```
"styles": [
"src/styles.css",
"src/more-styles.css",
{ "input": "src/lazy-style.scss", "lazy": true },
{ "input": "src/pre-rename-style.scss", "bundleName": "renamed-style" },
],
```
In Sass and Stylus you can make use of the `includePaths` functionality for both component and global styles,
which allows you to add extra base paths to be checked for imports.
To add paths, use the `stylePreprocessorOptions` build-target option:
```
"stylePreprocessorOptions": {
"includePaths": [
"src/style-paths"
]
},
```
You can then import files in the given folder (such as `src/style-paths/_variables.scss`)
anywhere in your project without the need for a relative path:
```
// src/app/app.component.scss
// A relative path works
@import '../style-paths/variables';
// But now this works as well
@import 'variables';
```
#### CSS preprocessor integration
To use a supported CSS preprocessor, add the URL for the preprocessor
to your component's `styleUrls` in the `@Component()` metadata.
For example:
```
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'app works!';
}
```
<div class="alert-is-helpful>
Style strings added directly to the `@Component() styles array must be written in CSS.
The CLI cannot apply a pre-processor to inline styles.
</div>

View File

@ -89,6 +89,189 @@ The root file names (`app.component`) are the same for both files.
Adopt these two conventions in your own projects for _every kind_ of test file.
{@a ci}
## Set up continuous integration
One of the best ways to keep your project bug free is through a test suite, but it's easy to forget to run tests all the time.
Continuous integration (CI) servers let you set up your project repository so that your tests run on every commit and pull request.
There are paid CI services like Circle CI and Travis CI, and you can also host your own for free using Jenkins and others.
Although Circle CI and Travis CI are paid services, they are provided free for open source projects.
You can create a public project on GitHub and add these services without paying.
Contributions to the Angular repo are automatically run through a whole suite of Circle CI and Travis CI tests.
This article explains how to configure your project to run Circle CI and Travis CI, and also update your test configuration to be able to run tests in the Chrome browser in either environment.
### Configure project for Circle CI
Step 1: Create a folder called `.circleci` at the project root.
Step 2: In the new folder, create a file called `config.yml` with the following content:
```
version: 2
jobs:
build:
working_directory: ~/my-project
docker:
- image: circleci/node:8-browsers
steps:
- checkout
- restore_cache:
key: my-project-{{ .Branch }}-{{ checksum "package.json" }}
- run: npm install
- save_cache:
key: my-project-{{ .Branch }}-{{ checksum "package.json" }}
paths:
- "node_modules"
- run: xvfb-run -a npm run test -- --single-run --no-progress --browser=ChromeNoSandbox
- run: xvfb-run -a npm run e2e -- --no-progress --config=protractor-ci.conf.js
```
This configuration caches `node_modules/` and uses [`npm run`](https://docs.npmjs.com/cli/run-script) to run CLI commands, because `@angular/cli` is not installed globally.
The double dash (`--`) is needed to pass arguments into the `npm` script.
For Chrome, it uses `xvfb-run` to run the `npm run` command using a virtual screen.
Step 3: Commit your changes and push them to your repository.
Step 4: [Sign up for Circle CI](https://circleci.com/docs/2.0/first-steps/) and [add your project](https://circleci.com/add-projects).
Your project should start building.
* Learn more about Circle CI from [Circle CI documentation](https://circleci.com/docs/2.0/).
### Configure project for Travis CI
Step 1: Create a file called `.travis.yml` at the project root, with the following content:
```
dist: trusty
sudo: false
language: node_js
node_js:
- "8"
addons:
apt:
sources:
- google-chrome
packages:
- google-chrome-stable
cache:
directories:
- ./node_modules
install:
- npm install
script:
# Use Chromium instead of Chrome.
- export CHROME_BIN=chromium-browser
- xvfb-run -a npm run test -- --single-run --no-progress --browser=ChromeNoSandbox
- xvfb-run -a npm run e2e -- --no-progress --config=protractor-ci.conf.js
```
This does the same things as the Circle CI configuration, except that Travis doesn't come with Chrome, so we use Chromium instead.
Step 2: Commit your changes and push them to your repository.
Step 3: [Sign up for Travis CI](https://travis-ci.org/auth) and [add your project](https://travis-ci.org/profile).
You'll need to push a new commit to trigger a build.
* Learn more about Travis CI testing from [Travis CI documentation](https://docs.travis-ci.com/).
### Configure CLI for CI testing in Chrome
When the CLI commands `ng test` and `ng e2e` are generally running the CI tests in your environment, you might still need to adjust your configuration to run the Chrome browser tests.
There are configuration files for both the [Karma JavaScript test runner](http://karma-runner.github.io/2.0/config/configuration-file.html)
and [Protractor](https://www.protractortest.org/#/api-overview) end-to-end testing tool,
which you must adjust to start Chrome without sandboxing.
* In the Karma configuration file, `karma.conf.js`, add a custom launcher called ChromeNoSandbox below browsers:
```
browsers: ['Chrome'],
customLaunchers: {
ChromeNoSandbox: {
base: 'Chrome',
flags: ['--no-sandbox']
}
},
```
* Create a new file, `protractor-ci.conf.js`, in the root folder of your project, which extends the original `protractor.conf.js`:
```
const config = require('./protractor.conf').config;
config.capabilities = {
browserName: 'chrome',
chromeOptions: {
args: ['--no-sandbox']
}
};
exports.config = config;
```
Now you can run the following commands to use the `--no-sandbox` flag:
```
ng test --single-run --no-progress --browser=ChromeNoSandbox
ng e2e --no-progress --config=protractor-ci.conf.js
```
{@a code-coverage}
## Enable code coverage reports
The CLI can run unit tests and create code coverage reports.
Code coverage reports show you any parts of our code base that may not be properly tested by your unit tests.
To generate a coverage report run the following command in the root of your project.
```
ng test --watch=false --code-coverage
```
When the tests are complete, the command creates a new `/coverage` folder 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, you can set the following option in the CLI configuration file, `angular.json`:
```
"test": {
"options": {
"codeCoverage": true
}
}
```
### Code coverage enforcement
The code coverage percentages let you estimate how much of your code is tested.
If your team decides on a set minimum amount to be unit tested, you can enforce this minimum with the Angular CLI.
For example, suppose you want the code base to have a minimum of 80% code coverage.
To enable this, open the [Karma](http://karma-runner.github.io/0.13/index.html) test platform configuration file, `karma.conf.js`, and add the following in the `coverageIstanbulReporter:` key.
```
coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true,
thresholds: {
statements: 80,
lines: 80,
branches: 80,
functions: 80
}
}
```
The `thresholds` property causes the tool to enforce a minimum of 80% code coverage when the unit tests are run in the project.
## Service Tests
Services are often the easiest files to unit test.

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@ -57,14 +57,14 @@
{
"url": "guide/docs-style-guide",
"title": "Doc authors style guide",
"tooltip": "Style guide for documentation authors",
"tooltip": "Style guide for documentation authors.",
"hidden": true
},
{
"url": "guide/quickstart",
"title": "Getting Started",
"tooltip": "A gentle introduction to Angular."
"tooltip": "A brief introduction to Angular and Angular CLI essentials."
},
{
@ -73,43 +73,43 @@
"children": [
{
"url": "tutorial",
"title": "1. Introduction",
"tooltip": "Part 1: Introduction to the Tour of Heroes tutorial"
"title": "Introduction",
"tooltip": "Introduction to the Tour of Heroes tutorial"
},
{
"url": "tutorial/toh-pt0",
"title": "2. The Application Shell",
"tooltip": "Part 2: Creating the application shell"
"title": "The Application Shell",
"tooltip": "Creating the application shell"
},
{
"url": "tutorial/toh-pt1",
"title": "3. The Hero Editor",
"tooltip": "Part 3: Build a simple hero editor"
"title": "1. The Hero Editor",
"tooltip": "Part 1: Build a simple hero editor"
},
{
"url": "tutorial/toh-pt2",
"title": "4. Displaying a List",
"tooltip": "Part 4: Build a master/detail page with a list of heroes."
"title": "2. Displaying a List",
"tooltip": "Part 2: Build a master/detail page with a list of heroes."
},
{
"url": "tutorial/toh-pt3",
"title": "5. Master/Detail Components",
"tooltip": "Part 5: Refactor the master/detail view into separate components."
"title": "3. Master/Detail Components",
"tooltip": "Part 3: Refactor the master/detail view into separate components."
},
{
"url": "tutorial/toh-pt4",
"title": "6. Services",
"tooltip": "Part 6: Create a reusable service to manage hero data."
"title": "4. Services",
"tooltip": "Part 4: Create a reusable service to manage hero data."
},
{
"url": "tutorial/toh-pt5",
"title": "7. Routing",
"tooltip": "Part 7: Add the Angular router and navigate among the views."
"title": "5. Routing",
"tooltip": "Part 5: Add the Angular router and navigate among the views."
},
{
"url": "tutorial/toh-pt6",
"title": "8. HTTP",
"tooltip": "Part 8: Use HTTP to retrieve and save hero data."
"title": "6. HTTP",
"tooltip": "Part 6: Use HTTP to retrieve and save hero data."
}
]
},
@ -210,14 +210,13 @@
}
]
},
{
"title": "Forms",
"tooltip": "Angular Forms",
"children": [
{
"url": "guide/forms-overview",
"title": "Forms Overview",
"title": "Introduction",
"tooltip": "A form creates a cohesive, effective, and compelling data entry experience. An Angular form coordinates a set of data-bound user controls, tracks changes, validates input, and presents errors."
},
{
@ -241,8 +240,8 @@
"tooltip": "Render dynamic forms with FormGroup."
}
]
},
{
},
{
"title": "Observables & RxJS",
"tooltip": "Observables & RxJS",
"children": [
@ -418,84 +417,29 @@
"tooltip": "Animate route transitions."
}
]
},
{
"url": "guide/testing",
"title": "Testing",
"tooltip": "Techniques and practices for testing an Angular app."
},
{
"url": "guide/cheatsheet",
"title": "Cheat Sheet",
"tooltip": "A quick guide to common Angular coding techniques."
}
]},
]
},
{
"title": "Techniques",
"tooltip": "Techniques for putting Angular to work in your environment",
"children": [
{
"url": "guide/i18n",
"title": "Internationalization (i18n)",
"tooltip": "Translate the app's template text into multiple languages."
},
{
"url": "guide/language-service",
"title": "Language Service",
"tooltip": "Use Angular Language Service to speed up dev time."
},
{
"url": "guide/security",
"title": "Security",
"tooltip": "Developing for content security in Angular applications."
},
{
"title": "Setup & Deployment",
"tooltip": "Setup and Deployment",
"children": [
{
"url": "guide/setup",
"title": "Setup for local development",
"tooltip": "Install the Angular QuickStart seed for faster, more efficient development on your machine."
},
{
"url": "guide/setup-systemjs-anatomy",
"title": "Anatomy of the Setup",
"tooltip": "Inside the local development environment for SystemJS."
},
{
"url": "guide/browser-support",
"title": "Browser Support",
"tooltip": "Browser support and polyfills guide."
},
{
"url": "guide/npm-packages",
"title": "Npm Packages",
"tooltip": "Recommended npm packages, and how to specify package dependencies."
},
{
"url": "guide/typescript-configuration",
"title": "TypeScript Configuration",
"tooltip": "TypeScript configuration for Angular developers."
},
{
"url": "guide/aot-compiler",
"title": "Ahead-of-Time Compilation",
"tooltip": "Learn why and how to use the Ahead-of-Time (AOT) compiler."
},
{
"url": "guide/deployment",
"title": "Deployment",
"tooltip": "Learn how to deploy your Angular app."
}
]
"url": "guide/i18n",
"title": "Internationalization (i18n)",
"tooltip": "Translate the app's template text into multiple languages."
},
{
"title": "Service Workers",
"title": "Service Workers & PWA",
"tooltip": "Angular service workers: Controlling caching of application resources.",
"children": [
{
@ -525,24 +469,108 @@
}
]
},
{
"url": "guide/universal",
"title": "Server-side Rendering",
"tooltip": "Render HTML server-side with Angular Universal."
}
]
},
{
"title": "Setup & Deployment",
"tooltip": "Setup, build, testing, and deployment environment and tool information.",
"children": [
{
"title": "Keeping Up-to-Date",
"tooltip": "Angular release practices, planning for updates, and update resources.",
"url": "guide/setup",
"title": "Setup for local development",
"tooltip": "Install the Angular QuickStart seed for faster, more efficient development on your machine.",
"hidden": true
},
{
"url": "guide/file-structure",
"title": "Project File Structure",
"tooltip": "Inside the local development environment for SystemJS."
},
{
"url": "guide/npm-packages",
"title": "Packages",
"tooltip": "Explanation of npm packages installed into a project by default."
},
{
"url": "guide/typescript-configuration",
"title": "TypeScript Configuration",
"tooltip": "TypeScript configuration for Angular developers."
},
{
"url": "guide/aot-compiler",
"title": "Ahead-of-Time Compilation",
"tooltip": "Learn why and how to use the Ahead-of-Time (AOT) compiler."
},
{
"url": "guide/build",
"title": "Building & Serving",
"tooltip": "Building and serving Angular apps."
},
{
"url": "guide/testing",
"title": "Testing",
"tooltip": "Techniques and practices for testing an Angular app."
},
{
"url": "guide/deployment",
"title": "Deployment",
"tooltip": "Learn how to deploy your Angular app."
},
{
"url": "guide/browser-support",
"title": "Browser Support",
"tooltip": "Browser support and polyfills guide."
},
{
"title": "Dev Tool Integration",
"tooltip": "Integration with your development environment and tool information.",
"children": [
{
"url": "guide/updating",
"title": "Updating Your Projects",
"tooltip": "Information about updating Angular applications and libraries to the latest version."
},
{
"url": "guide/releases",
"title": "Angular Releases",
"tooltip": "Angular versioning, release, support, and deprecation policies and practices."
}
{
"url": "guide/language-service",
"title": "Language Service",
"tooltip": "Use Angular Language Service to speed up dev time."
},
{
"url": "guide/visual-studio-2015",
"title": "Visual Studio 2015 QuickStart",
"tooltip": "Use Visual Studio 2015 with the QuickStart files."
}
]
},
{
"url": "guide/setup-systemjs-anatomy",
"title": "Anatomy of the Setup",
"tooltip": "Inside the local development environment for SystemJS.",
"hidden": true
}
]
},
{
"title": "Release Information",
"tooltip": "Angular release practices, updating, and upgrading.",
"children": [
{
"url": "guide/releases",
"title": "Angular Releases",
"tooltip": "Angular versioning, release, support, and deprecation policies and practices."
},
{
"url": "guide/updating",
"title": "Keeping Up-to-Date",
"tooltip": "Information about updating Angular applications and libraries to the latest version."
},
{
"title": "Upgrading from AngularJS",
"tooltip": "Incrementally upgrade an AngularJS application to Angular.",
@ -552,27 +580,25 @@
"title": "Upgrading Instructions",
"tooltip": "Incrementally upgrade an AngularJS application to Angular."
},
{
"url": "guide/upgrade-performance",
"title": "Upgrading for Performance",
"tooltip": "Upgrade from AngularJS to Angular in a more flexible way."
},
{
"url": "guide/ajs-quick-reference",
"title": "AngularJS-Angular Concepts",
"tooltip": "Learn how AngularJS concepts and techniques map to Angular."
}
]
},
}
]
},
{
"title": "Quick Reference",
"tooltip": "Summaries of Angular syntax, coding, and terminology.",
"children": [
{
"url": "guide/universal",
"title": "Server-side Rendering",
"tooltip": "Render HTML server-side with Angular Universal."
},
{
"url": "guide/visual-studio-2015",
"title": "Visual Studio 2015 QuickStart",
"tooltip": "Use Visual Studio 2015 with the QuickStart files."
"url": "guide/cheatsheet",
"title": "Cheat Sheet",
"tooltip": "A quick guide to common Angular coding techniques."
},
{
"url": "guide/styleguide",
@ -589,7 +615,7 @@
{
"title": "API",
"tooltip": "Details of the Angular classes and values.",
"tooltip": "Details of the Angular packages, classes, interfaces, and other types.",
"url": "api"
},
{