2017年1月12日 星期四

[ASP.NET Core X Angular] (14) - Server side rendering for SEO

 Angular    ASP.NET Core     SEO     Server side rendering    Angular Universal




Introduction


We take great advantage of better UX and performance in SPA (
Single Page Application), but dealing with SEO is a headache since SPA doesn’t perform well against the indexing of web crawler.

The best way for building a SEO friendly SPA is using server-side rendering.

In my previous article,

We can render a MVC view from server side in angular component, but honestly, this way has some integration issues and is not easy to maintain.

So we will use Angular Universal and Microsoft.AspNetCore.SpaServices to build a server-side-rendering single page app.


Related articles


Angular Universal

Angular Universal does server-side-rendering and serves the single pages as what they behave on the client side.

PS. There will be a chance (?) for integrating
Angular Universal to Angular CLI, follow issues: #1050, #3013.
 
Here are some ways to use Angular Universal quickly,



Microsoft.AspNetCore.SpaServices

This package enables the following functions for building SPA with Angular 2, React, Knockout… in ASP.NET Core.




▌Implement


Since it’s fairly complex to integrate Microsoft.AspNetCore.SpaServices and Angular Universal, there is a quick way to get started with Angular2 server-side rendering on ASP.NET Core: aspnetcore-spa generator.


Install

webpack

$> npm install -g webpack


aspnetcore-spa generator

$> npm install -g yo generator-aspnetcore-spa




Create New project

Under an empty folder, use the following command to create a new project.

$> yo aspnetcore-spa


And execute  dotnet restore  and  npm install after the project is created.






PS. You can also create the SPA project by installing ASP.NET Core Template Pack extension.


Server side rendering

Okay, take a look the view-source of our previous non-server-side-rendering app in the browser.








And now we implement the same codes on the template generated from aspnetcore-spa generator. With Angular Universal and ASP.NET Core SPA Services, we have a server-side rendering app now! 





Hot module replacement (Demo)





Summary


With Angular Universal, we can quickly build a SEO friendly Single page application with Angular2. Also Angular Universal will support more backend frameworks in the near future!


Angular Universal was originally built to work with a node.js back-end. There are adapters for most popular node.js server-side frameworks such as Express or Hapi.js. In addition to node.js, however, Angular Universal has ASP.NET Core support. In the near future we hope to add support for Java, PHP and Python.

- From Angular Universal document




Reference





沒有留言:

張貼留言