应用外壳
App shell
应用外壳是一种在构建期间借助路由渲染部分应用的方法。它可以通过快速启动一个静态渲染页面(所有页面的公共骨架)来改善用户体验。与此同时,浏览器会下载完整的客户端版本,并在代码加载后自动切换到完整版。
Application shell is a way to render a portion of your application using a route at build time. It can improve the user experience by quickly launching a static rendered page (a skeleton common to all pages) while the browser downloads the full client version and switches to it automatically after the code loads.
这能让用户快速看到应用中第一个有意义的画面,因为浏览器可以渲染出 HTML 和 CSS,而无需初始化任何 JavaScript。
This gives users a meaningful first paint of your application that appears quickly because the browser can render the HTML and CSS without the need to initialize any JavaScript.
欲知详情,参阅应用外壳模型。
Learn more in The App Shell Model.
第 1 步:准备本应用
Step 1: Prepare the application
可以用下列 CLI 命令来执行本操作:
You can do this with the following CLI command:
ng new my-app --routing
对于既有应用,你必须手动添加 RouterModule
并在应用中定义 <router-outlet>
。
For an existing application, you have to manually add the RouterModule
and defining a <router-outlet>
within your application.
第 2 步:创建应用外壳
Step 2: Create the app shell
使用 CLI 自动创建一个应用外壳。
Use the CLI to automatically create the application shell.
ng generate app-shell
client-project
是你这个客户端应用的名字。
For more information about this command see App shell command.
执行完这个命令,你会发现 angular.json
配置文件中已经增加了两个新目标,并做了一些其它更改。
After running this command you will notice that the angular.json
configuration file has been updated to add two new targets, with a few other changes.
"server": {
"builder": "@angular-devkit/build-angular:server",
"defaultConfiguration": "production",
"options": {
"outputPath": "dist/my-app/server",
"main": "src/main.server.ts",
"tsConfig": "tsconfig.server.json"
},
"configurations": {
"development": {
"outputHashing": "none",
},
"production": {
"outputHashing": "media",
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"sourceMap": false,
"optimization": true
}
}
},
"app-shell": {
"builder": "@angular-devkit/build-angular:app-shell",
"defaultConfiguration": "production",
"options": {
"route": "shell"
},
"configurations": {
"development": {
"browserTarget": "my-app:build:development",
"serverTarget": "my-app:server:development",
},
"production": {
"browserTarget": "my-app:build:production",
"serverTarget": "my-app:server:production"
}
}
}
第 3 步:验证该应用是使用应用外壳的内容构建的
Step 3: Verify the app is built with the shell content
使用 CLI 构建目标 app-shell
。
Use the CLI to build the app-shell
target.
ng run my-app:app-shell:development
或使用产品环境配置。
Or to use the production configuration.
ng run my-app:app-shell:production
要验证构建的输出,请打开 dist/my-app/browser/index.html
。寻找默认的文本 app-shell works!
就可以验证这个应用外壳路由确实是作为输出的一部分渲染出来的。
To verify the build output, open dist/my-app/browser/index.html
. Look for default text app-shell works!
to show that the application shell route was rendered as part of the output.