使用 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 是一個開發(fā) Single Page Application 的框架,在瀏覽器端執(zhí)行。這意味著 Angular 應(yīng)用在客戶端渲染,而不是服務(wù)器端。
Angular is not SEO friendly by default.
默認(rèn)實(shí)現(xiàn)里,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 應(yīng)用,我們在 body 標(biāo)簽頁下能看到完整的頁面內(nèi)容。但是像 Angular 這種 SPA 應(yīng)用,我們只能看到 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>上面這個應(yīng)用無法被網(wǎng)絡(luò)爬蟲爬取,因?yàn)?app-root selector 里什么也沒有包含。
如何讓一個 Angular 應(yīng)用支持 SSR.
運(yùn)行命令:ng add @nguniversal/express-engine
首先運(yùn)行如下命令進(jìn)行構(gòu)建:
npm run build:ssr
生成了如下新的文件夾:
browser 文件夾下面,全是為了瀏覽器端渲染而使用的資源:
而 server 文件夾里包含的資源,則是為了在服務(wù)器端運(yùn)行 JavaScript 而準(zhǔn)備的。
如何啟動 Angular Universal 應(yīng)用?
npm run serve:ssr
背后的原理,其實(shí)就是啟動 nodejs 應(yīng)用:
serve:ssr": “node dist/server/main.js”,
當(dāng)服務(wù)端收到直接對前端路由URL的請求時,不是直接把index.html當(dāng)做404頁面發(fā)回去,而是在內(nèi)存中啟動一個Angular框架,執(zhí)行出結(jié)果,然后把內(nèi)存中生成的DOM內(nèi)容發(fā)回去。
從原理上看,它只是拿v8引擎執(zhí)行了一段JS代碼而已。雖然渲染出了HTML,但并沒有借助瀏覽器的渲染引擎(也就是說連PhantomJS們都不用)。
更多Jerry的原創(chuàng)文章,盡在:“汪子熙”:
總結(jié)
以上是生活随笔為你收集整理的使用 Angular Universal 实现服务器端渲染的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Angular 服务器端渲染的学习笔记(
- 下一篇: Angular Universal 学习