An article exploring server-side rendering (SSR) in Angular
Generally speaking, ordinary Angular applications run in browsers, render pages in the DOM, and interact with users. Angular Universal renders on the server-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 to eBay, 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.
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
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
-
Express web server running file
- main.server .ts
- 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
- package.json
package.json, some npm scripts will be automatically added:
dev:ssr is used to run the SSR version in the development environment;
serve:ssr is used to directly run the build or prerendered web page;
build:ssr is used to build the SSR version of the web page;
prerender Builds pre-rendered web pages. Different from
build, the HTML files of these pages will be generated based on the provided
routes.
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 objectswindow,
document,
navigator,
location in the browser.
Location and
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'); } }
使用 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<any>, 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 的场景下不会再出问题。
Prerender 预渲染静态 HTML
经过上面的步骤后,如果我们通过 npm run build:ssr
构建项目,你会发现在 dist/<your project>/browser
下面只有 index.html
文件,打开文件查看,发现其中还有 <app-root></app-root>
这样的元素,也就是说你的网页内容并没有在 html 中生成。这是因为 Angular 使用了动态路由,比如 /product/:id
这种路由,而页面的渲染结果要经过 JS 的执行才能知道,因此,Angular 使用了 Express 作为 Web 服务器,能在服务端运行时根据用户请求(爬虫请求)使用模板引擎生成静态 HTML 界面。
而 prerender
(npm run prerender
)会在构建时生成静态 HTML 文件。比如我们做企业官网,只有几个页面,那么我们可以使用预渲染技术生成这几个页面的静态 HTML 文件,避免在运行时动态生成,从而进一步提升网页的访问速度和用户体验。
预渲染路径配置
需要进行预渲染(预编译 HTML)的网页路径,可以有几种方式进行提供:
通过命令行的附加参数:
ng run <app-name>: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 <app-name>: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/<your project>/browser
下的 index.html
会发现里面没有 <app-root></app-root>
了,取而代之的是主页的实际内容。同时也生成了相应的路径目录以及各个目录下的 index.html
子页面文件。
SEO 优化
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



This article continues the learning of Angular, takes you to understand the metadata and decorators in Angular, and briefly understands their usage. I hope it will be helpful to everyone!

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

Do you know Angular Universal? It can help the website provide better SEO support!

This article will share with you an Angular practical experience and learn how to quickly develop a backend system using angualr combined with ng-zorro. I hope it will be helpful to everyone!

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

The Angular project is too large, how to split it reasonably? The following article will introduce to you how to reasonably split Angular projects. I hope it will be helpful to you!
