LoginSignup
9
7

More than 3 years have passed since last update.

Blazor WebAssemblyのアプリケーションをGitHub Actionsを使ってGithub Pagesにデプロイする

Last updated at Posted at 2020-03-20

はじめに

タイトル通りの内容の手順の備忘録です.
リポジトリ

(2020/12/22) バージョン等を一部更新

Blazor WebAssemblyのプロジェクト

Blazor WebAssemblyはASP.NET Core 3.1ではまだPreviewなので,テンプレートのインストールが必要です.
dotnet new --install Microsoft.AspNetCore.Components.WebAssembly.Templates::3.2.0-preview2.20160.5

インストール後,テンプレートからBlazor WebAssemblyのプロジェクトを作成します.

SPAをGitHub Pagesに展開するために

URLの書き換えを処理することでSingle Page ApplicationをGitHub Pages上に展開することができるそうです.
詳しくは ASP.NET Core Blazor WebAssembly をホストしてデプロイする をご確認ください.

URLの変更

base URLを username.github.io/repogitory にするためにwwwroot下にあるindex.htmlbaseタグにリポジトリ名を追加します.

index.html
<head>
    <title>HelloBlazorWasm</title>
    <base href="/HelloBlazorWasm/"/>
</head>

また,ローカル環境のIIS Expressサーバで実行する際にも,変更したURLで実行するために,Properties/launchSettings.jsoniisSettingsapplicationUrlも変更します.

launchSettings.json
"iisSettings": {
  "windowsAuthentication": false,
  "anonymousAuthentication": true,
  "iisExpress": {
    "applicationUrl": "http://localhost:xxxxx/HelloBlazorWasm",
    "sslPort": xxxxx
}

SPA対応

まず,index.htmlbody内の_framework/blazor.webassembly.jsを読み込む前にSPAのルーティングを設定します.詳しくは Single Page Apps for GitHub Pages をご確認ください.

index.html
<body>
<app>Loading...</app>

<!-- Start Single Page Apps for GitHub Pages -->
<script type="text/javascript">
    // Single Page Apps for GitHub Pages
    // https://github.com/rafrex/spa-github-pages
    // Copyright (c) 2016 Rafael Pedicini, licensed under the MIT License
    // ----------------------------------------------------------------------
    // This script checks to see if a redirect is present in the query string
    // and converts it back into the correct url and adds it to the
    // browser's history using window.history.replaceState(...),
    // which won't cause the browser to attempt to load the new url.
    // When the single page app is loaded further down in this file,
    // the correct url will be waiting in the browser's history for
    // the single page app to route accordingly.
    (function(l) {
        if (l.search) {
            var q = {};
            l.search.slice(1).split('&').forEach(function(v) {
                var a = v.split('=');
                q[a[0]] = a.slice(1).join('=').replace(/~and~/g, '&');
            });
            if (q.p !== undefined) {
                window.history.replaceState(null,
                    null,
                    l.pathname.slice(0, -1) +
                    (q.p || '') +
                    (q.q ? ('?' + q.q) : '') +
                    l.hash
                );
            }
        }
    }(window.location))
</script>
<!-- End Single Page Apps for GitHub Pages -->

<!-- 何かしらの処理 -->

<script src="_framework/blazor.webassembly.js"></script>
</body>

次に,wwwroot下に以下の内容で404.htmlを作成します.

404.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Single Page Apps for GitHub Pages</title>
    <script type="text/javascript">
        // Single Page Apps for GitHub Pages
        // https://github.com/rafrex/spa-github-pages
        // Copyright (c) 2016 Rafael Pedicini, licensed under the MIT License
        // ----------------------------------------------------------------------
        // This script takes the current url and converts the path and query
        // string into just a query string, and then redirects the browser
        // to the new url with only a query string and hash fragment,
        // e.g. http://www.foo.tld/one/two?a=b&c=d#qwe, becomes
        // http://www.foo.tld/?p=/one/two&q=a=b~and~c=d#qwe
        // Note: this 404.html file must be at least 512 bytes for it to work
        // with Internet Explorer (it is currently > 512 bytes)
        // If you're creating a Project Pages site and NOT using a custom domain,
        // then set segmentCount to 1 (enterprise users may need to set it to > 1).
        // This way the code will only replace the route part of the path, and not
        // the real directory in which the app resides, for example:
        // https://username.github.io/repo-name/one/two?a=b&c=d#qwe becomes
        // https://username.github.io/repo-name/?p=/one/two&q=a=b~and~c=d#qwe
        // Otherwise, leave segmentCount as 0.
        var segmentCount = 0;
        var l = window.location;
        l.replace(
            l.protocol +
            '//' +
            l.hostname +
            (l.port ? ':' + l.port : '') +
            l.pathname.split('/').slice(0, 1 + segmentCount).join('/') +
            '/?p=/' +
            l.pathname.slice(1).split('/').slice(segmentCount).join('/').replace(/&/g, '~and~') +
            (l.search ? '&q=' + l.search.slice(1).replace(/&/g, '~and~') : '') +
            l.hash
        );
    </script>
</head>
<body>
</body>
</html>

そして,wwwroot下に中身が空の.nojekyllファイルを作成します.

GitHubActions用のymlの設定

GitHub Actionsで自動化するために,設定ファイルを作成します.
こちらの設定ファイルでは,masterブランチに変更があった際に,dotnet publishコマンドで生成されたファイルをGitHub Pages用のgh-pagesブランチにpushします.

gh-pages.yml
name: Deploy to Github Pages

on:
  push:
    branches: [ master ]
  pull_request:
    branches: [ master ]

jobs:
  build:
    runs-on: ubuntu-latest

    # Steps represent a sequence of tasks that will be executed as part of the job
    steps:
    # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
    - uses: actions/checkout@v2

    # .NET Core環境の構築
    - name: Setup .NET Core SDK
      uses: actions/setup-dotnet@v1.7.2
      with:
      # Blazor WebAssemblyが使えるSDKを指定
        dotnet-version: 3.1.x
    - name: Build Application
      # デプロイするProjectを指定 (今回は"HelloBlazorWasm")
      run: dotnet publish -c Release ./HelloBlazorWasm/HelloBlazorWasm.csproj

    - name: Deploy
      uses: peaceiris/actions-gh-pages@v3
      with:
           github_token: ${{ secrets.GITHUB_TOKEN }}
           # publishコマンドで出力されたファイルをgh-pagesブランチにpush
           publish_dir: ./HelloBlazorWasm/bin/Release/netstandard2.1/publish/wwwroot/

GitHub Pagesの設定

GitHubリポジトリのSettings -> GitHub Pages -> Sourcegh-pages branchに変更します.

おわりに

BlazorのHello Worldをデプロイした結果
ほぼ参考記事通りの内容ですが,GitHub Actionsを初めて使ったので,勉強もかねてまとめてみました.
GitHub Pagesだとコストも掛からないので,遊びで作ったアプリでも気軽に公開できそうです.

参考

  1. ASP.NET Core Blazor WebAssembly をホストしてデプロイする
  2. Blazorで作成したウェブサイトをGitHub Pagesで公開する
  3. Single Page Apps for GitHub Pages
  4. Blazor WebAssembly を GitHub Actions で GitHub Pages に発行する
9
7
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
9
7