Storybook で「[MSW] Failed to register a Service Worker for scope ('https://username.github.io/') with script ('https://reponame.github.io/mockServiceWorker.js'): Service Worker script does not exist at the given path.」が発生した場合の対処法

Storybook と Mock Service Worker を使ったプロジェクトを GitHub Pages にデプロイしたらエラーになった場合の対処法を備忘録として残す。

エラー

Storybook を GitHub Pages へデプロイした際に下記のようなエラーが表示されてしまいました。

[MSW] Failed to register a Service Worker for scope ('https://splendente.github.io/') with script ('https://splendente.github.io/mockServiceWorker.js'): Service Worker script does not exist at the given path.

GitHub PagesにデプロイしたStorybook上でMock Service Workerのエラーが表示されている画像

MSW(Mock Service Worker)のスクリプトファイルである mockServiceWorker.js が見つからないことが原因です。

GitHub Pages にデプロイすると、URLが https://{ユーザー名}.github.io/{リポジトリ名}/ となります。

そのため、mockServiceWorker.js のパスがルートに向いてるとエラーのようにファイルが見つけられないようです。

対象法

GitHub Pages では mockServiceWorker.js のパスを /リポジトリ名/mockServiceWorker.js と指定すると解消します。

.storybook/preview.(js or ts) を下記のように変更します。

let options = {};
if (location.hostname === "自分のユーザー名.github.io") {
  options = {
    serviceWorker: {
      url: "/リポジトリ名/mockServiceWorker.js",
    },
  };
}

// Initialize MSW
initialize(options);