# Conflicts: # aio/content/guide/ajs-quick-reference.md # aio/content/guide/animations.md # aio/content/guide/aot-compiler.md # aio/content/guide/architecture-components.md # aio/content/guide/architecture-modules.md # aio/content/guide/architecture-next-steps.md # aio/content/guide/architecture-services.md # aio/content/guide/architecture.md # aio/content/guide/attribute-directives.md # aio/content/guide/bootstrapping.md # aio/content/guide/browser-support.md # aio/content/guide/cheatsheet.md # aio/content/guide/comparing-observables.md # aio/content/guide/component-interaction.md # aio/content/guide/component-styles.md # aio/content/guide/dependency-injection-in-action.md # aio/content/guide/dependency-injection-pattern.md # aio/content/guide/dependency-injection.md # aio/content/guide/deployment.md # aio/content/guide/displaying-data.md # aio/content/guide/dynamic-component-loader.md # aio/content/guide/elements.md # aio/content/guide/feature-modules.md # aio/content/guide/form-validation.md # aio/content/guide/forms.md # aio/content/guide/glossary.md # aio/content/guide/hierarchical-dependency-injection.md # aio/content/guide/i18n.md # aio/content/guide/lazy-loading-ngmodules.md # aio/content/guide/lifecycle-hooks.md # aio/content/guide/ngmodule-faq.md # aio/content/guide/ngmodule-vs-jsmodule.md # aio/content/guide/ngmodules.md # aio/content/guide/npm-packages.md # aio/content/guide/observables-in-angular.md # aio/content/guide/observables.md # aio/content/guide/pipes.md # aio/content/guide/practical-observable-usage.md # aio/content/guide/providers.md # aio/content/guide/quickstart.md # aio/content/guide/reactive-forms.md # aio/content/guide/router.md # aio/content/guide/rx-library.md # aio/content/guide/security.md # aio/content/guide/service-worker-communications.md # aio/content/guide/service-worker-getting-started.md # aio/content/guide/service-worker-intro.md # aio/content/guide/setup-systemjs-anatomy.md # aio/content/guide/setup.md # aio/content/guide/singleton-services.md # aio/content/guide/structural-directives.md # aio/content/guide/styleguide.md # aio/content/guide/template-syntax.md # aio/content/guide/testing.md # aio/content/guide/typescript-configuration.md # aio/content/guide/universal.md # aio/content/guide/updating.md # aio/content/guide/upgrade.md # aio/content/guide/user-input.md # aio/content/guide/visual-studio-2015.md # aio/content/marketing/docs.md # aio/content/navigation.json # aio/content/tutorial/toh-pt0.md # aio/content/tutorial/toh-pt1.md # aio/content/tutorial/toh-pt2.md # aio/content/tutorial/toh-pt3.md # aio/content/tutorial/toh-pt4.md # aio/content/tutorial/toh-pt5.md # aio/content/tutorial/toh-pt6.md # aio/ngsw-manifest.json # aio/package.json # aio/src/app/custom-elements/api/api-list.component.html # aio/src/app/custom-elements/api/api-list.component.ts # aio/src/index.html # aio/tools/transforms/templates/api/base.template.html # aio/tools/transforms/templates/api/class.template.html # aio/tools/transforms/templates/api/directive.template.html # aio/tools/transforms/templates/api/enum.template.html # aio/tools/transforms/templates/api/includes/class-overview.html # aio/tools/transforms/templates/api/includes/deprecation.html # aio/tools/transforms/templates/api/includes/export-as.html # aio/tools/transforms/templates/api/includes/info-bar.html # aio/tools/transforms/templates/api/includes/interface-overview.html # aio/tools/transforms/templates/api/includes/selectors.html # aio/tools/transforms/templates/api/lib/directiveHelpers.html # aio/tools/transforms/templates/api/lib/githubLinks.html # aio/tools/transforms/templates/api/lib/memberHelpers.html # aio/tools/transforms/templates/api/package.template.html # aio/yarn.lock # packages/common/http/src/module.ts # packages/common/src/common_module.ts # packages/common/src/directives/ng_for_of.ts # packages/common/src/directives/ng_if.ts # packages/common/src/directives/ng_template_outlet.ts # packages/common/src/location/location.ts # packages/common/src/pipes/async_pipe.ts # packages/common/src/pipes/json_pipe.ts # packages/common/src/pipes/number_pipe.ts # packages/common/src/pipes/slice_pipe.ts # packages/core/src/change_detection/change_detector_ref.ts # packages/core/src/di/injectable.ts # packages/core/src/linker/template_ref.ts # packages/core/src/linker/view_container_ref.ts # packages/core/src/metadata/di.ts # packages/core/src/metadata/ng_module.ts # packages/core/src/render/api.ts # packages/forms/src/directives/form_interface.ts # packages/forms/src/directives/ng_form.ts # packages/forms/src/directives/ng_model.ts # packages/forms/src/directives/reactive_directives/form_control_name.ts # packages/forms/src/directives/select_control_value_accessor.ts # packages/forms/src/directives/validators.ts # packages/forms/src/form_providers.ts # packages/forms/src/model.ts # packages/forms/src/validators.ts # packages/router/src/config.ts # packages/router/src/router.ts # packages/router/src/router_module.ts # packages/router/src/router_state.ts
24 KiB
Deployment
部署
When you are ready to deploy your Angular application to a remote server, you have various options for deployment.
当你准备把 Angular 应用部署到远程服务器上时,有很多关于部署的选项。
{@a dev-deploy}
{@a copy-files}
Simplest deployment possible
最简化的部署方式
For the simplest deployment, build for development and copy the output directory to a web server.
最简化的部署方式就是为开发环境构建,并把其输出复制到 Web 服务器上。
-
Start with the development build:
使用开发环境进行构建
-
Copy everything within the output folder (
dist/by default) to a folder on the server.把输出目录(默认为
dist/)下的每个文件都复制到到服务器上的某个目录下。 -
Configure the server to redirect requests for missing files to
index.html. Learn more about server-side redirects below.配置服务器,让缺失的文件都重定向到
index.html上。 欲知详情,参见稍后的服务端重定向部分。
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. For the next steps in deployment, see Optimize for production.
这不是生产环境部署。它没有优化过,对最终用户来说也不快。 但是,这足够用来跟管理者、团队成员和其它涉众在内部分享你的进度和想法了。 部署的下一个步骤,参见为生产环境优化。
{@a deploy-to-github}
Deploy to GitHub pages
发布到 GitHub pages(页面服务)
Another simple way to deploy your Angular app is to use GitHub Pages.
另一种发布 Angular 应用的简单途径是使用 GitHub Pages。
-
You need to create a GitHub account if you don't have one, and then create a repository for your project. Make a note of the user name and project name in GitHub.
你需要创建一个 GitHub 账号(如果没有的话),然后为你的项目创建一个仓库。记下 GitHub 中的用户名和项目名。
-
Build your project using Github project name, with the Angular CLI command
ng buildand the options shown here:使用 Angular CLI 命令
ng build --prod --output-path docs --base-hrefng build来构建这个 GitHub 项目,选项如下: -
When the build is complete, make a copy of
docs/index.htmland name itdocs/404.html.当构建完成时,把
docs/index.html复制为docs/404.html。 -
Commit your changes and push.
提交你的更改,并推送。
-
On the GitHub project page, configure it to publish from the docs folder.
在 GitHub 的项目页中,把该项目配置为从 docs 目录下发布。
You can see your deployed page at https://<user_name>.github.io/<project_name>/.
你可以到 https://<user_name>.github.io/<project_name>/ 中查看部署好的页面。
参见 angular-cli-ghpages,这个包用到了全部这些特性,还提供了一些额外功能。
{@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
带路由的应用必须以 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.
Angular 应用很适合用简单的静态 HTML 服务器提供服务。 你不需要服务端引擎来动态合成应用页面,因为 Angular 会在客户端完成这件事。
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.
如果该应用使用 Angular 路由器,你就必须配置服务器,让它对不存在的文件返回应用的宿主页(index.html)。
{@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.
带路由的应用应该支持“深链接”。
所谓深链接就是指一个 URL,它用于指定到应用内某个组件的路径。
比如,http://www.mysite.com/heroes/42 就是一个到英雄详情页面的深链接,用于显示 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.
当用户从运行中的客户端应用导航到这个 URL 时,这没问题。 Angular 路由器会拦截这个 URL,并且把它路由到正确的页面。
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 — 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.
但是,当从邮件中点击链接或在浏览器地址栏中输入它或仅仅在英雄详情页刷新下浏览器时,所有这些操作都是由浏览器本身处理的,在应用的控制范围之外。 浏览器会直接向服务器请求那个 URL,路由器没机会插手。
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.
静态服务器会在收到对 http://www.mysite.com/ 的请求时返回 index.html,但是会拒绝对 http://www.mysite.com/heroes/42 的请求,
并返回一个 404 - Not Found 错误,除非,它被配置成了返回 index.html。
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 CLI 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.
在开发期间,CLI 命令 ng serve 能让你在本地浏览器中运行你的应用。
每当你保存文件时,CLI 就会重新编译该应用,并刷新浏览器,来加载最新编译的应用。
The app is hosted in local memory and served on http://localhost:4200/, using webpack-dev-server.
该应用运行在本地内存里,并使用 webpack-dev-server 来在 http://localhost:4200/ 端口上提供服务。
{@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; like webpack-dev-server, it can automatically reload your browser when you write new files.
在开发的后期阶段,你可能会希望让应用更接近部署后的行为方式。
这时,你可以把发布目录(dist)输出到磁盘上,但还要安装另一个 Web 服务器。
可以尝试安装 lite-server,像 webpack-dev-server 一样,当你修改了文件时,它可以自动刷新浏览器。
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.
要想获得实时刷新(live-reload)的体验,你需要运行两个终端。
第一个在监视模式下运行 build 命令,把应用随时编译到 dist 目录下。
第二个针对 dist 目录运行 Web 服务器。
这两个过程组合起来,提供了与 ng serve 相同的行为。
-
Start the build in terminal A:
在终端 A 中启动构建:
-
Start the web server in terminal B:
在终端 B 中启动 Web 服务器:
The default browser opens to the appropriate URL.
默认的浏览器会打开相应的 URL。
-
Lite-Server: the default dev server installed with the Quickstart repo is pre-configured to fallback to
index.html.Lite-Server是"快速上手"仓库中安装的默认开发服务器,它被预先配置为回退到
index.html。 -
Webpack-Dev-Server: setup the
historyApiFallbackentry in the dev server options as follows:Webpack-Dev-Server在开发服务器的配置中设置了
historyApiFallback: { disableDotRule: true, htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'] }historyApiFallback,代码如下:
Production servers
生产服务器
-
Apache: add a rewrite rule to the
.htaccessfile as shown (https://ngmilk.rocks/2015/03/09/angularjs-html5-mode-or-pretty-urls-on-apache-using-htaccess/):Apache:在
RewriteEngine On # 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].htaccess文件中添加一个重写规则, 代码如下(出处):# If the requested resource doesn't exist, use index.html RewriteRule ^ /index.html
-
Nginx: use
try_files, as described in Front Controller Pattern Web Apps, modified to serveindex.html:NGinx:使用
try_files $uri $uri/ /index.html;try_files指向index.html,详细描述见Web 应用的前端控制器模式。 -
IIS: add a rewrite rule to
<system.webServer> <rewrite> <rules> <rule name="Angular Routes" stopProcessing="true"> <match url=".*" /> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="/index.html" /> </rule> </rules> </rewrite> </system.webServer>web.config, similar to the one shown here: -
GitHub Pages: you can't directly configure the GitHub Pages server, but you can add a 404 page. Copy
index.htmlinto404.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 fromdocs/on master and to create a.nojekyllfileGitHub 页面服务:你没办法直接配置 Github 的页面服务,但可以添加一个 404 页,只要把
index.html复制到404.html就可以了。 它仍然会给出一个 404 响应,但是浏览器将会正确处理该页,并正常加载该应用。 使用在主分支的docs/下启动服务 并创建一个.nojekyll文件也是一个好办法。 -
Firebase hosting: add a rewrite rule.
Firebase 主机服务:添加一条重写规则。
"rewrites": [ { "source": "**", "destination": "/index.html" } ]
{@a cors}
Requesting services from a different server (CORS)
请求来自另一个服务器的服务(CORS)
Angular developers may encounter a cross-origin resource sharing 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.
Angular 开发者在向与该应用的宿主服务器不同域的服务器发起请求时,可能会遇到一种跨域资源共享(CORS)错误。 浏览器会阻止该请求,除非得到那台服务器的明确许可。
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 enable-cors.org.
客户端应用对这种错误无能为力。 服务器必须配置成可以接受来自该应用的请求。 要了解如何对特定的服务器开启 CORS,参见enable-cors.org。
{@a optimize}
Optimize for production
Although deploying directly from the development environment works,
you can generate an optimized build with additional CLI command line flags,
starting with --prod.
Build with --prod
ng build --prodThe --prod meta-flag engages the following optimization features.
- Ahead-of-Time (AOT) Compilation: pre-compiles Angular component templates.
- Production mode: deploys the production environment which enables production mode.
- Bundling: concatenates your many application and library files into a few bundles.
- Minification: removes excess whitespace, comments, and optional tokens.
- Uglification: rewrites code to use short, cryptic variable and function names.
- Dead code elimination: removes unreferenced modules and much unused code.
The remaining copy deployment steps are the same as before.
See ng build for more about CLI build options and what they do.
{@a enable-prod-mode}
Enable production mode
Angular apps run in development mode by default, as you can see by the following message on the browser console:
Angular is running in the development mode. Call enableProdMode() to enable the production mode.Switching to production mode can make it run faster by disabling development specific checks such as the dual change detection cycles.
Building for production (or appending the --environment=prod flag) enables production mode
Look at the CLI-generated main.ts to see how this works.
{@a lazy-loading}
Lazy loading
You can dramatically reduce launch time by only loading the application modules that absolutely must be present when the app starts.
Configure the Angular Router to defer loading of all other modules (and their associated code), either by waiting until the app has launched or by lazy loading them on demand.
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, 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
which automatically recognizes lazy-loaded NgModules and creates separate bundles for them.
{@a measure}
Measure performance
You can make better decisions about what to optimize and how when you have a clear and accurate understanding of what's making the application slow. The cause may not be what you think it is. You can waste a lot of time and money optimizing something that has no tangible benefit or even makes the app slower. You should measure the app's actual behavior when running in the environments that are important to you.
The Chrome DevTools Network Performance page is a good place to start learning about measuring performance.
The WebPageTest tool is another good choice that can also help verify that your deployment was successful.
{@a inspect-bundle}
Inspect the bundles
The source-map-explorer tool is a great way to inspect the generated JavaScript bundles after a production build.
Install source-map-explorer:
Build your app for production including the source maps
ng build --prod --source-mapList the generated bundles in the dist/ folder.
Run the explorer to generate a graphical representation of one of the bundles. The following example displays the graph for the main bundle.
node_modules/.bin/source-map-explorer dist/main.*.bundle.jsThe source-map-explorer analyzes the source map generated with the bundle and draws a map of all dependencies,
showing exactly which classes are included in the bundle.
Here's the output for the main bundle of the QuickStart.
{@a base-tag}
The base tag
The HTML <base href="..."/>
specifies a base path for resolving relative URLs to assets such as images, scripts, and style sheets.
For example, given the <base href="/my/app/">, the browser resolves a URL such as some/place/foo.jpg
into a server request for my/app/some/place/foo.jpg.
During navigation, the Angular router uses the base href as the base path to component, template, and module files.
See also the APP_BASE_HREF alternative.
In development, you typically start the server in the folder that holds index.html.
That's the root folder and you'd add <base href="/"> near the top of index.html because / is the root of the app.
But on the shared or production server, you might serve the app from a subfolder.
For example, when the URL to load the app is something like http://www.mysite.com/my/app/,
the subfolder is my/app/ and you should add <base href="/my/app/"> to the server version of the index.html.
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.
Building and serving for deployment
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.
Both ng build and ng serve clear the output folder before they build the project, but only the ng build command writes the generated build artifacts to the output folder.
The output folder is dist/ by default.
To output to a different folder, change the outputPath in angular.json.
The ng 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 ng build command.
ng build --watch
Like the ng serve command, this regenerates output files when source files change.
For complete details of the CLI commands, see the CLI command reference.