使用 Angular Universal 实现服务器端渲染
原文鏈接:https://medium.com/geekculture/implement-server-side-rendering-using-angular-universal-b32ebd9b8b29
Normally Angular is a framework that is used to build Single Page Applications (SPA’s) and executes on the browser which means angular application renders on the client-side, not on the server-side.
通常意義來講,Angular 是一個開發 Single Page Application 的框架,在瀏覽器端執行。這意味著 Angular 應用在客戶端渲染,而不是服務器端。
Angular is not SEO friendly by default.
默認實現里,Angular 并不是 SEO 友好。
When we run any other Non-single page application on the browser then what we see there, we can see the complete content of our web pages there under the body tag. but in the case of Single Page Applications like Angular, we only see our root selector that is holding all the source code behind the scene and does not render source code at the client-side on the browser.
對于 Non SPA 應用,我們在 body 標簽頁下能看到完整的頁面內容。但是像 Angular 這種 SPA 應用,我們只能看到 Root selector,該 selector 背后容納了所有的渲染源代碼。
例子:
<!doctype html> <html lang="en"> <head><meta charset="utf-8"><title>MyAwesomeApp</title><base href="/"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="icon" type="image/x-icon" href="favicon.ico"> </head> <body><app-root></app-root> <script src="runtime.js" defer></script><script src="polyfills.js" defer></script><script src="styles.js" defer></script><script src="vendor.js" defer></script><script src="main.js" defer></script></body> </html>上面這個應用無法被網絡爬蟲爬取,因為 app-root selector 里什么也沒有包含。
如何讓一個 Angular 應用支持 SSR.
運行命令:ng add @nguniversal/express-engine
首先運行如下命令進行構建:
npm run build:ssr
生成了如下新的文件夾:
browser 文件夾下面,全是為了瀏覽器端渲染而使用的資源:
而 server 文件夾里包含的資源,則是為了在服務器端運行 JavaScript 而準備的。
如何啟動 Angular Universal 應用?
npm run serve:ssr
背后的原理,其實就是啟動 nodejs 應用:
serve:ssr": “node dist/server/main.js”,
當服務端收到直接對前端路由URL的請求時,不是直接把index.html當做404頁面發回去,而是在內存中啟動一個Angular框架,執行出結果,然后把內存中生成的DOM內容發回去。
從原理上看,它只是拿v8引擎執行了一段JS代碼而已。雖然渲染出了HTML,但并沒有借助瀏覽器的渲染引擎(也就是說連PhantomJS們都不用)。
更多Jerry的原創文章,盡在:“汪子熙”:
總結
以上是生活随笔為你收集整理的使用 Angular Universal 实现服务器端渲染的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Angular 服务器端渲染的学习笔记(
- 下一篇: 元气骑士爆米花怎么得(『元气骑士』5.0