共计 2481 个字符,预计需要花费 7 分钟才能阅读完成。
https://github.com/angular/un…
Universal 的命名由来:
We believe that using the word “universal” is correct when referring to a JavaScript Application that runs in more environments than the browser. (inspired by Universal JavaScript)
参考了一个能运行在除浏览器之外的其余环境下的 JavaScript 利用。
Angular Express Engine
This is an Express Engine for running Angular Apps on the server for server side rendering.
可能让 Angular 利用运行在服务器端。
应用形式:
import * as express from 'express';
import {ngExpressEngine} from '@nguniversal/express-engine';
const app = express();
// Set the engine
app.engine(
'html',
ngExpressEngine({bootstrap: ServerAppModule, // Give it a module to bootstrap}),
);
app.set('view engine', 'html');
app.get('/**/*', (req: Request, res: Response) => {
res.render('../dist/index', {
req,
res,
});
});
留神:我在 server.ts 里做了批改,加上了 console.log:
须要执行 npm run build:ssr 之后,server.ts 的批改,才会呈现在 dist/server/main.js 里去:
并且这个 console.log, 因为代码是执行在服务器端的,所以只有在启动 nodejs 利用的控制台里能力看到 log:
至于客户端浏览器里看到的这些 JavaScript:
来自 dist/browser 文件夹:
另一篇文章:https://dzone.com/articles/an…
什么是服务器端渲染
The server returns a static web page fully complied with dynamic data ready to display on the browser.
The fetching of the dynamic data is done by server-side scripts written by server-side languages.
动态数据的获取是运行服务器端脚本而实现的。留神上图:在服务器端渲染模式下,服务器返回给客户端的页面,蕴含了页面布局和所有的数据,即数据的 Viewable. 而加上 Client-side scripts 的辅助后,页面从纯正的 layout,变成了 Viewable 和 intractable.
This is how we used to render web pages in the old days (PHP/ Perl/CGI), and it has recently gained traction with technologies, such as React and Express. It is SEO friendly and great for devices with low power.
实际上,PHP, JSP 就是采纳这种形式渲染网页的。
The server returns a complete static web page with all the elements required to display the browser and the client-side scripts required to make the page dynamic.
服务器返回的是:一个齐全动态的网页,蕴含了所有显示在浏览器里所必须的元素,以及客户端层面的脚本。这些脚本能够用来让页面具备动态效果。
再看客户端渲染:
The server returns a partial web page with no dynamic data, but it provides the client-side scripts necessary to fetch the data on demand asynchronously.
服务器返回给客户端的是一个空的模板,不蕴含任何数据。通过客户端脚本,在客户端执行,异步获取数据。
The client is responsible for fetching the data upon loading a new page or based on user interaction. There are many Async calls to the server. CSR is not SEO friendly, as the content is always dynamic.
客户端负责在加载新页面或者基于用户响应时去异步加载数据。因为内容是齐全动静的,对 SEO 不敌对。
using the new Angular Schematic, we are going to configure the application as server-side rendering (SSR).
应用 Angular Schematic,能够将 Angular 利用配置成反对 SSR.
三个最重要的依赖:
- @angular/platform-server
- @nguniversal/express-engine
- express
The server has delivered a completely static HTML page with all elements in pure SSR.
在 SSR 模式下,服务器返回了纯动态的 HTML 页面,蕴含了所有的 DOM element.
The client-side script is only needed for user interaction and is not responsible for fetching the data.
客户端脚本只负责响应用户动作,不再负责数据读取。
更多 Jerry 的原创文章,尽在:” 汪子熙 ”: