LoginSignup
0
0

More than 3 years have passed since last update.

angular universalをnetlifyへ導入する

Last updated at Posted at 2021-02-23

angular universalをnetlifyへ導入する

angularは、SPA(Single Page Application)のため、クローラからインデックスされにくいため、SSR(Server Side Rendering)を導入することで、インデックスされやすくする。

angularのSSRとしてUniversalがあります。
angular公式サイトの Universal 紹介ページ

universalの追加

自プロジェクトに下記コマンドで追加します。

ng add @nguniversal/express-engine

コマンドが正常にすれば、
server.ts
src/app/app.server.module.ts
src/main.server.ts
tsconfig.server.json
が追加される。

追加が完了したら、prerenderを実行してみます。

npm run prerender

つづいて、netlify.tomlを作成します。
自プロジェクトの直下に保存しておけば、build時に読み込まれます。

netlify.toml
[build]
 command = "npm run prerender"
 functions = "./functions"
 publish = "dist/[自プロジェクト]/browser"

その他

SSRにより、server側のrender処理では、window,localStorageなどが使えないため、isPlatformBrowser()を使用してserver側とbrowser側の処理を分ける必要がある。

import { PLATFORM_ID, Inject } from '@angular/core';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';

export class SomeComponent {
    constructor(
        @Inject(PLATFORM_ID) private platformId: any) {
        // 処理...
    }

    ngOnInit():void {
        if (isPlatformBrowser(this.platformId)) {
            // browser側の処理...
        }
        if (isPlatformServer(this.platformId)) {
            // // server側の処理...
        }
    }
}

参考ページ

netlifyのcommunityに投稿されていた記事
https://www.netlify.com/blog/2021/02/08/pre-rendering-with-angular-universal/

以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0