日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

使用 Angular Universal 实现服务器端渲染

發布時間:2023/12/19 编程问答 53 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用 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 实现服务器端渲染的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。