Generally speaking, ordinary Angular applications run inbrowsers, render pages in the DOM, and interact with users. Angular Universal renders on theserver-side(Server-Side Rendering, SSR), generates static application web pages, and then displays them on the client. The advantage is that it can be rendered faster and provides a complete Content display can be provided to users before interaction. [Related tutorial recommendations: "angular tutorial"]
This article is completed in the Angular 14 environment. Some content may not be applicable to the new Angular version. Please refer to Angular official document.
Although some websites including Google now Search engines and social media claim to already support crawling SPA (Single-Page Application) applications driven by JavaScript (JS), but the results seem to be unsatisfactory. The SEO performance of static HTML websites is still better than that of dynamic websites, which is also the view held by Angular's official website (Angular is owned by Google!).
Universal can generate a static version of the application without JS, and has better support for search, external links, and navigation.
Some mobile devices may not support JS or have very limited support for JS, resulting in a very poor website access experience. In this case, we need to provide a JS-free version of the app to provide a better experience for users.
For the user experience, the speed of displaying the homepage is crucial. According toeBay, every 100 milliseconds faster search results are displayed increases "add to cart" usage by 0.5%.
After using Universal, the home page of the application will be displayed to the user in a complete form. This is a pure HTML web page, which can be displayed even if JS is not supported. At this time, although the web page cannot handle browser events, it supports jumping throughrouterLink.
ng add @nguniversal/express-engine
It is recommended to commit all changes before running this command.This command will make the following modifications to the project:
- Server main program file
- Server application main module
- TypeScript server configuration file
-
Expressweb server running file- Add the dependencies required for SSR and run the script
- Add the configuration required to develop and build SSR applications
package.json, some npm scripts will be automatically added:
dev:ssris used to run the SSR version in the development environment;
serve:ssris used to directly run the build or prerendered web page;
build:ssris used to build the SSR version of the web page;
prerenderBuilds pre-rendered web pages. Different from
build, the HTML files of these pages will be generated based on the provided
routes.
window,
document,
navigator,
locationin the browser.
Locationand
DOCUMENT.
window.location.href, and after changing it to SSR, the code is as follows:
import { Location } from '@angular/common'; export class AbmNavbarComponent implements OnInit{ // ctor 中注入 Location constructor(private _location:Location){ //... } ngOnInit() { // 打印当前地址 console.log(this._location.path(true)); } }
document.getElementById()to obtain DOM elements in the browser, after changing to SSR, the code is as follows:
import { DOCUMENT } from '@angular/common'; export class AbmFoxComponent implements OnInit{ // ctor 中注入 DOCUMENT constructor(@Inject(DOCUMENT) private _document: Document) { } ngOnInit() { // 获取 id 为 fox-container 的 DOM const container = this._document.getElementById('fox-container'); } }
在 Angular SSR 应用中,HTTP 请求的 URL 地址必须为绝对地址(即,以http/https
开头的地址,不能是相对地址,如/api/heros
)。Angular 官方推荐将请求的 URL 全路径设置到renderModule()
或renderModuleFactory()
的options
参数中。但是在 v14 自动生成的代码中,并没有显式调用这两个方法的代码。而通过读 Http 请求的拦截,也可以达到同样的效果。
下面我们先准备一个拦截器,假设文件位于项目的shared/universal-relative.interceptor.ts
路径:
import { HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { Inject, Injectable, Optional } from '@angular/core'; import { REQUEST } from '@nguniversal/express-engine/tokens'; import { Request } from 'express'; // 忽略大小写检查 const startsWithAny = (arr: string[] = []) => (value = '') => { return arr.some(test => value.toLowerCase().startsWith(test.toLowerCase())); }; // http, https, 相对协议地址 const isAbsoluteURL = startsWithAny(['http', '//']); @Injectable() export class UniversalRelativeInterceptor implements HttpInterceptor { constructor(@Optional() @Inject(REQUEST) protected request: Request) { } intercept(req: HttpRequest, next: HttpHandler) { // 不是绝对地址的 URL if (!isAbsoluteURL(req.url)) { let protocolHost: string; if (this.request) { // 如果注入的 REQUEST 不为空,则从注入的 SSR REQUEST 中获取协议和地址 protocolHost = `${this.request.protocol}://${this.request.get( 'host' )}`; } else { // 如果注入的 REQUEST 为空,比如在进行 prerender build: // 这里需要添加自定义的地址前缀,比如我们的请求都是从 abmcode.com 来。 protocolHost = 'https://www.abmcode.com'; } const pathSeparator = !req.url.startsWith('/') ? '/' : ''; const url = protocolHost + pathSeparator + req.url; const serverRequest = req.clone({ url }); return next.handle(serverRequest); } else { return next.handle(req); } } }
然后在app.server.module.ts
文件中 provide 出来:
import { UniversalRelativeInterceptor } from './shared/universal-relative.interceptor'; // ... 其他 imports @NgModule({ imports: [ AppModule, ServerModule, // 如果你用了 @angular/flext-layout,这里也需要引入服务端模块 FlexLayoutServerModule, ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: UniversalRelativeInterceptor, multi: true } ], bootstrap: [AppComponent], }) export class AppServerModule { }
这样任何对于相对地址的请求都会自动转换为绝对地址请求,在 SSR 的场景下不会再出问题。
经过上面的步骤后,如果我们通过npm run build:ssr
构建项目,你会发现在dist/
下面只有index.html
文件,打开文件查看,发现其中还有
这样的元素,也就是说你的网页内容并没有在 html 中生成。这是因为 Angular 使用了动态路由,比如/product/:id
这种路由,而页面的渲染结果要经过 JS 的执行才能知道,因此,Angular 使用了 Express 作为 Web 服务器,能在服务端运行时根据用户请求(爬虫请求)使用模板引擎生成静态 HTML 界面。
而prerender
(npm run prerender
)会在构建时生成静态 HTML 文件。比如我们做企业官网,只有几个页面,那么我们可以使用预渲染技术生成这几个页面的静态 HTML 文件,避免在运行时动态生成,从而进一步提升网页的访问速度和用户体验。
需要进行预渲染(预编译 HTML)的网页路径,可以有几种方式进行提供:
通过命令行的附加参数:
ng run:prerender --routes /product/1 /product/2
如果路径比较多,比如针对product/:id
这种动态路径,则可以使用一个路径文件:
routes.txt
/products/1 /products/23 /products/145 /products/555
然后在命令行参数指定该文件:
ng run:prerender --routes-file routes.txt
在项目的angular.json
文件配置需要的路径:
"prerender": { "builder": "@nguniversal/builders:prerender", "options": { "routes": [ // 这里配置 "/", "/main/home", "/main/service", "/main/team", "/main/contact" ] },
配置完成后,重新执行预渲染命令(npm run prerender
或者使用命令行参数则按照上面<1><2>中的命令执行),编译完成后,再打开dist/
下的index.html
会发现里面没有
了,取而代之的是主页的实际内容。同时也生成了相应的路径目录以及各个目录下的index.html
子页面文件。
SEO 的关键在于对网页title
,keywords
和description
的收录,因此对于我们想要让搜索引擎收录的网页,可以修改代码提供这些内容。
在 Angular 14 中,如果路由界面通过Routes
配置,可以将网页的静态title
直接写在路由的配置中:
{ path: 'home', component: AbmHomeComponent, title: '<你想显示在浏览器 tab 上的标题>' },
另外,Angular 也提供了可注入的Title
和Meta
用于修改网页的标题和 meta 信息:
import { Meta, Title } from '@angular/platform-browser'; export class AbmHomeComponent implements OnInit { constructor( private _title: Title, private _meta: Meta, ) { } ngOnInit() { this._title.setTitle('<此页的标题>'); this._meta.addTags([ { name: 'keywords', content: '<此页的 keywords,以英文逗号隔开>' }, { name: 'description', content: '<此页的描述>' } ]); } }
Angular 作为 SPA 企业级开发框架,在模块化、团队合作开发方面有自己独到的优势。在进化到 v14 这个版本中提供了不依赖NgModule
的独立Component
功能,进一步简化了模块化的架构。
Angular Universal 主要关注将 Angular App 如何进行服务端渲染和生成静态 HTML,对于用户交互复杂的 SPA 并不推荐使用 SSR。针对页面数量较少、又有 SEO 需求的网站或系统,则可以考虑使用 Universal 和 SSR 技术。
更多编程相关知识,请访问:编程教学!!
The above is the detailed content of An article exploring server-side rendering (SSR) in Angular. For more information, please follow other related articles on the PHP Chinese website!