{ "id": "guide/build", "title": "Building and serving Angular apps", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Building and serving Angular appslink

\n

This page discusses build-specific configuration options for Angular projects.

\n\n

Configuring application environmentslink

\n

You can define different named build configurations for your project, such as stage and production, with different defaults.

\n

Each named configuration can have defaults for any of the options that apply to the various builder targets, such as build, serve, and test. The Angular CLI build, serve, and test commands can then replace files with appropriate versions for your intended target environment.

\n

Configure environment-specific defaultslink

\n

A project's src/environments/ folder contains the base configuration file, environment.ts, which provides a default environment.\nYou can add override defaults for additional environments, such as production and staging, in target-specific configuration files.

\n

For example:

\n\n└──myProject/src/environments/\n └──environment.ts\n └──environment.prod.ts\n └──environment.stage.ts\n\n

The base file environment.ts, contains the default environment settings. For example:

\n\nexport const environment = {\n production: false\n};\n\n

The build command uses this as the build target when no environment is specified.\nYou can add further variables, either as additional properties on the environment object, or as separate objects.\nFor example, the following adds a default for a variable to the default environment:

\n\nexport const environment = {\n production: false,\n apiUrl: 'http://my-api-url'\n};\n\n

You can add target-specific configuration files, such as environment.prod.ts.\nThe following sets content sets default values for the production build target:

\n\nexport const environment = {\n production: true,\n apiUrl: 'http://my-prod-url'\n};\n\n

Using environment-specific variables in your applink

\n

The following application structure configures build targets for production and staging environments:

\n\n└── src\n └── app\n ├── app.component.html\n └── app.component.ts\n └── environments\n ├── environment.prod.ts\n ├── environment.staging.ts\n └── environment.ts\n\n

To use the environment configurations you have defined, your components must import the original environments file:

\n\nimport { environment } from './../environments/environment';\n\n

This ensures that the build and serve commands can find the configurations for specific build targets.

\n

The following code in the component file (app.component.ts) uses an environment variable defined in the configuration files.

\n\nimport { Component } from '@angular/core';\nimport { environment } from './../environments/environment';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n constructor() {\n console.log(environment.production); // Logs false for default environment\n }\n title = 'app works!';\n}\n\n\n

Configure target-specific file replacementslink

\n

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 in the TypeScript program with a target-specific version of that file.\nThis is useful for including target-specific code or variables in a build that targets a specific environment, such as production or staging.

\n

By default no files are replaced.\nYou can add file replacements for specific build targets.\nFor example:

\n\n\"configurations\": {\n \"production\": {\n \"fileReplacements\": [\n {\n \"replace\": \"src/environments/environment.ts\",\n \"with\": \"src/environments/environment.prod.ts\"\n }\n ],\n ...\n\n

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.

\n

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:

\n\n\"configurations\": {\n \"production\": { ... },\n \"staging\": {\n \"fileReplacements\": [\n {\n \"replace\": \"src/environments/environment.ts\",\n \"with\": \"src/environments/environment.staging.ts\"\n }\n ]\n }\n}\n\n

You can add more configuration options to this target environment as well.\nAny option that your build supports can be overridden in a build target configuration.

\n

To build using the staging configuration, run the following command:

\n\n ng build --configuration=staging\n\n

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:

\n\n\"serve\": {\n \"builder\": \"@angular-devkit/build-angular:dev-server\",\n \"options\": {\n \"browserTarget\": \"your-project-name:build\"\n },\n \"configurations\": {\n \"production\": {\n \"browserTarget\": \"your-project-name:build:production\"\n },\n \"staging\": {\n \"browserTarget\": \"your-project-name:build:staging\"\n }\n }\n},\n\n\n\n

Configuring size budgetslink

\n

As applications grow in functionality, they also grow in size.\nThe CLI allows you to set size thresholds in your configuration to ensure that parts of your application stay within size boundaries that you define.

\n

Define your size boundaries in the CLI configuration file, angular.json, in a budgets section for each configured environment.

\n\n{\n ...\n \"configurations\": {\n \"production\": {\n ...\n budgets: []\n }\n }\n}\n\n

You can specify size budgets for the entire app, and for particular parts.\nEach budget entry configures a budget of a given type.\nSpecify size values in the following formats:

\n\n

When you configure a budget, the build system warns or reports an error when a given part of the app reaches or exceeds a boundary size that you set.

\n

Each budget entry is a JSON object with the following properties:

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PropertyValue
type\n

The type of budget. One of:

\n
    \n
  • \n

    bundle - The size of a specific bundle.

    \n
  • \n
  • \n

    initial - The initial size of the app.

    \n
  • \n
  • \n

    allScript - The size of all scripts.

    \n
  • \n
  • \n

    all - The size of the entire app.

    \n
  • \n
  • \n

    anyComponentStyle - This size of any one component stylesheet.

    \n
  • \n
  • \n

    anyScript - The size of any one script.

    \n
  • \n
  • \n

    any - The size of any file.

    \n
name\n

The name of the bundle (for type=bundle).

\n
baselineThe baseline size for comparison.
maximumWarningThe maximum threshold for warning relative to the baseline.
maximumErrorThe maximum threshold for error relative to the baseline.
minimumWarningThe minimum threshold for warning relative to the baseline.
minimumErrorThe minimum threshold for error relative to the baseline.
warningThe threshold for warning relative to the baseline (min & max).
errorThe threshold for error relative to the baseline (min & max).
\n\n\n\n

Configuring CommonJS dependencieslink

\n
\n

It is recommended that you avoid depending on CommonJS modules in your Angular applications.\nDepending on CommonJS modules can prevent bundlers and minifiers from optimizing your application, which results in larger bundle sizes.\nInstead, it is recommended that you use ECMAScript modules in your entire application.\nFor more information, see How CommonJS is making your bundles larger.

\n
\n

The Angular CLI outputs warnings if it detects that your browser application depends on CommonJS modules.\nTo disable these warnings, you can add the CommonJS module name to allowedCommonJsDependencies option in the build options located in angular.json file.

\n\n\"build\": {\n \"builder\": \"@angular-devkit/build-angular:browser\",\n \"options\": {\n \"allowedCommonJsDependencies\": [\n \"lodash\"\n ]\n ...\n }\n ...\n},\n\n\n

Configuring browser compatibilitylink

\n

The CLI uses Autoprefixer to ensure compatibility with different browser and browser versions.\nYou may find it necessary to target specific browsers or exclude certain browser versions from your build.

\n

Internally, Autoprefixer relies on a library called Browserslist to figure out which browsers to support with prefixing.\nBrowserlist looks for configuration options in a browserslist property of the package configuration file, or in a configuration file named .browserslistrc.\nAutoprefixer looks for the browserslist configuration when it prefixes your CSS.

\n\n\n \"browserslist\": [\n \"> 1%\",\n \"last 2 versions\"\n ]\n\n\n\n ### Supported Browsers\n > 1%\n last 2 versions\n\n

See the browserslist repo for more examples of how to target specific browsers and versions.

\n

Backward compatibility with Lighthouselink

\n

If you want to produce a progressive web app and are using Lighthouse to grade the project, add the following browserslist entry to your package.json file, in order to eliminate the old flexbox prefixes:

\n\n\"browserslist\": [\n \"last 2 versions\",\n \"not ie <= 10\",\n \"not ie_mob <= 10\"\n]\n\n

Backward compatibility with CSS gridlink

\n

CSS grid layout support in Autoprefixer, which was previously on by default, is off by default in Angular 8 and higher.

\n

To use CSS grid with IE10/11, you must explicitly enable it using the autoplace option.\nTo do this, add the following to the top of the global styles file (or within a specific css selector scope):

\n\n/* autoprefixer grid: autoplace */\n\n

or

\n\n/* autoprefixer grid: no-autoplace */\n\n

For more information, see Autoprefixer documentation.

\n\n

Proxying to a backend serverlink

\n

You can use the proxying support in the webpack dev server to divert certain URLs to a backend server, by passing a file to the --proxy-config build option.\nFor example, to divert all calls for http://localhost:4200/api to a server running on http://localhost:3000/api, take the following steps.

\n
    \n
  1. \n

    Create a file proxy.conf.json in your project's src/ folder.

    \n
  2. \n
  3. \n

    Add the following content to the new proxy file:

    \n\n{\n \"/api\": {\n \"target\": \"http://localhost:3000\",\n \"secure\": false\n }\n}\n\n
  4. \n
  5. \n

    In the CLI configuration file, angular.json, add the proxyConfig option to the serve target:

    \n\n...\n\"architect\": {\n \"serve\": {\n \"builder\": \"@angular-devkit/build-angular:dev-server\",\n \"options\": {\n \"browserTarget\": \"your-application-name:build\",\n \"proxyConfig\": \"src/proxy.conf.json\"\n },\n...\n\n
  6. \n
  7. \n

    To run the dev server with this proxy configuration, call ng serve.

    \n
  8. \n
\n

You can edit the proxy configuration file to add configuration options; some examples are given below.\nFor a description of all options, see webpack DevServer documentation.

\n

Note that if you edit the proxy configuration file, you must relaunch the ng serve process to make your changes effective.

\n

Rewrite the URL pathlink

\n

The pathRewrite proxy configuration option lets you rewrite the URL path at run time.\nFor example, you can specify the following pathRewrite value to the proxy configuration to remove \"api\" from the end of a path.

\n\n{\n \"/api\": {\n \"target\": \"http://localhost:3000\",\n \"secure\": false,\n \"pathRewrite\": {\n \"^/api\": \"\"\n }\n }\n}\n\n

If you need to access a backend that is not on localhost, set the changeOrigin option as well. For example:

\n\n{\n \"/api\": {\n \"target\": \"http://npmjs.org\",\n \"secure\": false,\n \"pathRewrite\": {\n \"^/api\": \"\"\n },\n \"changeOrigin\": true\n }\n}\n\n

To help determine whether your proxy is working as intended, set the logLevel option. For example:

\n\n{\n \"/api\": {\n \"target\": \"http://localhost:3000\",\n \"secure\": false,\n \"pathRewrite\": {\n \"^/api\": \"\"\n },\n \"logLevel\": \"debug\"\n }\n}\n\n

Proxy log levels are info (the default), debug, warn, error, and silent.

\n

Proxy multiple entrieslink

\n

You can proxy multiple entries to the same target by defining the configuration in JavaScript.

\n

Set the proxy configuration file to proxy.conf.js (instead of proxy.conf.json), and specify configuration files as in the following example.

\n\nconst PROXY_CONFIG = [\n {\n context: [\n \"/my\",\n \"/many\",\n \"/endpoints\",\n \"/i\",\n \"/need\",\n \"/to\",\n \"/proxy\"\n ],\n target: \"http://localhost:3000\",\n secure: false\n }\n]\n\nmodule.exports = PROXY_CONFIG;\n\n

In the CLI configuration file, angular.json, point to the JavaScript proxy configuration file:

\n\n...\n\"architect\": {\n \"serve\": {\n \"builder\": \"@angular-devkit/build-angular:dev-server\",\n \"options\": {\n \"browserTarget\": \"your-application-name:build\",\n \"proxyConfig\": \"src/proxy.conf.js\"\n },\n...\n\n

Bypass the proxylink

\n

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.

\n\nconst PROXY_CONFIG = {\n \"/api/proxy\": {\n \"target\": \"http://localhost:3000\",\n \"secure\": false,\n \"bypass\": function (req, res, proxyOptions) {\n if (req.headers.accept.indexOf(\"html\") !== -1) {\n console.log(\"Skipping proxy for browser request.\");\n return \"/index.html\";\n }\n req.headers[\"X-Custom-Header\"] = \"yes\";\n }\n }\n}\n\nmodule.exports = PROXY_CONFIG;\n\n

Using corporate proxylink

\n

If you work behind a corporate proxy, the backend cannot directly proxy calls to any URL outside your local network.\nIn this case, you can configure the backend proxy to redirect calls through your corporate proxy using an agent:

\n\nnpm install --save-dev https-proxy-agent\n\n

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.

\n

Use the following content in the JavaScript configuration file.

\n\nvar HttpsProxyAgent = require('https-proxy-agent');\nvar proxyConfig = [{\n context: '/api',\n target: 'http://your-remote-server.com:3000',\n secure: false\n}];\n\nfunction setupForCorporateProxy(proxyConfig) {\n var proxyServer = process.env.http_proxy || process.env.HTTP_PROXY;\n if (proxyServer) {\n var agent = new HttpsProxyAgent(proxyServer);\n console.log('Using corporate proxy server: ' + proxyServer);\n proxyConfig.forEach(function(entry) {\n entry.agent = agent;\n });\n }\n return proxyConfig;\n}\n\nmodule.exports = setupForCorporateProxy(proxyConfig);\n\n\n \n
\n\n\n" }