An article exploring server-side rendering (SSR) in Angular

青灯夜游
Release: 2022-12-27 19:24:07
forward
2010 people have browsed it

An article exploring server-side rendering (SSR) in Angular

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.

Benefits of using SSR

More friendly to SEO

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.

Improve mobile performance

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.

Display the homepage faster

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 through

routerLink.

The advantage of this is that we can use a static web page to grab the user's attention first, and load the entire Angular application at the same time when the user browses the web page. This gives users a very good and extremely fast loading experience.

Add SSR to the project

Angular CLI can help us convert an ordinary Angular project into a project with SSR very conveniently. Creating a server-side application only requires one command:

ng add @nguniversal/express-engine
Copy after login
It is recommended to commit all changes before running this command.

This command will make the following modifications to the project:

  • Add the server file:

    • main.server .ts- Server main program file
    • app/app.server.module.ts- Server application main module
    • tsconfig. server.json- TypeScript server configuration file
    • server.ts-Expressweb server running file
  • Modified file:

    • package.json- Add the dependencies required for SSR and run the script
    • angular.json- Add the configuration required to develop and build SSR applications
In

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 frombuild, the HTML files of these pages will be generated based on the providedroutes.

Replacement of Browser API

Because Universal apps are not executed in the browser, some browser APIs or features will not be available. For example, server-side applications cannot use the global objects

window,document,navigator,locationin the browser.

Angular provides two injectable objects for replacing equivalent objects on the server side:

LocationandDOCUMENT.

For example, in the browser, we obtain the address of the current browser through

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)); } }
Copy after login

Similarly , for using

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'); } }
Copy after login

使用 URL 绝对地址

在 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); } } }
Copy after login

然后在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 { }
Copy after login

这样任何对于相对地址的请求都会自动转换为绝对地址请求,在 SSR 的场景下不会再出问题。

Prerender 预渲染静态 HTML

经过上面的步骤后,如果我们通过npm run build:ssr构建项目,你会发现在dist//browser下面只有index.html文件,打开文件查看,发现其中还有这样的元素,也就是说你的网页内容并没有在 html 中生成。这是因为 Angular 使用了动态路由,比如/product/:id这种路由,而页面的渲染结果要经过 JS 的执行才能知道,因此,Angular 使用了 Express 作为 Web 服务器,能在服务端运行时根据用户请求(爬虫请求)使用模板引擎生成静态 HTML 界面。

prerendernpm run prerender)会在构建时生成静态 HTML 文件。比如我们做企业官网,只有几个页面,那么我们可以使用预渲染技术生成这几个页面的静态 HTML 文件,避免在运行时动态生成,从而进一步提升网页的访问速度和用户体验。

预渲染路径配置

需要进行预渲染(预编译 HTML)的网页路径,可以有几种方式进行提供:

  • 通过命令行的附加参数:

    ng run :prerender --routes /product/1 /product/2
    Copy after login
  • 如果路径比较多,比如针对product/:id这种动态路径,则可以使用一个路径文件:

    routes.txt

    /products/1 /products/23 /products/145 /products/555
    Copy after login

    然后在命令行参数指定该文件:

    ng run :prerender --routes-file routes.txt
    Copy after login
  • 在项目的angular.json文件配置需要的路径:

    "prerender": { "builder": "@nguniversal/builders:prerender", "options": { "routes": [ // 这里配置 "/", "/main/home", "/main/service", "/main/team", "/main/contact" ] },
    Copy after login

配置完成后,重新执行预渲染命令(npm run prerender或者使用命令行参数则按照上面<1><2>中的命令执行),编译完成后,再打开dist//browser下的index.html会发现里面没有了,取而代之的是主页的实际内容。同时也生成了相应的路径目录以及各个目录下的index.html子页面文件。

SEO 优化

SEO 的关键在于对网页titlekeywordsdescription的收录,因此对于我们想要让搜索引擎收录的网页,可以修改代码提供这些内容。

在 Angular 14 中,如果路由界面通过Routes配置,可以将网页的静态title直接写在路由的配置中:

{ path: 'home', component: AbmHomeComponent, title: '<你想显示在浏览器 tab 上的标题>' },
Copy after login

另外,Angular 也提供了可注入的TitleMeta用于修改网页的标题和 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: '<此页的描述>' } ]); } }
Copy after login

总结

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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!