LoginSignup
3
0
記事投稿キャンペーン 「2024年!初アウトプットをしよう」

Storybookのtitleタグやfaviconを無理やり変更する

Last updated at Posted at 2024-01-05

Storybookで自作のライブラリのドキュメントサイトを作ったのですが、そうなると当然titleタグやfaviconを独自のものに変更したいわけですが、正規の設定ではできないっぽい?ので無理やり変更しました。

初期レンダリング時のtitleタグを変更

index.htmlに静的に設定される初期レンダリング時のtitleタグですが、どうせ直後にStorybookによって動的に変更されるため、あまり意味はありません。

ただ、シェア時などにシェア先のボットが読みに来る際は、js実行前の静的なhtmlを参照するため、こちらも一応変更しておきたいです。

Storybookの設定でどうこうしようと考えるのはやめて、ビルドされて生成されたhtmlファイルを書き換えちゃいましょう。

htmlファイルを読み込んで、titleタグ部分を文字列置き換えして上書きするスクリプトを作成します。

bashでもなんでもいいんですが、今回はnode.jsで作成しました。

update-title.js
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

const SITE_TITLE = '変更後のタイトル'

// ビルド後のhtmlまでのパス
const filePath = path.join(__dirname, 'storybook-static/index.html')

fs.readFile(filePath, 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading the HTML file:', err)
    return
  }
  const updatedData = data.replace(/<title>.*<\/title>/, `<title>${SITE_TITLE}</title>`)

  fs.writeFile(filePath, updatedData, 'utf8', (writeErr) => {
    if (writeErr) {
      console.error('Error writing the updated HTML file:', writeErr)
      return
    }
    console.log('Title updated successfully.')
  })
})

これをビルドスクリプトの後に実行されるようにします。

package.json
  "scripts": {
    "dev": "storybook dev -p 6006",
-   "build": "storybook build"
+   "build": "storybook build && node update-title.js"
  },

動的に設定されるtitleタグを変更

Storybookは、ページ遷移時などにtitleタグを以下のような内容に更新します。

[ページ名]  Storybook

ユーザーが実際に目にするtitleは、htmlファイルの静的なtitleタグではなくこちらになります。

また、Googleのクローラーもjsを実行した後のhtmlを読むため、SEO観点でもこちらが参照されます。

MutationObserverというクラスはDOMの書き換えを監視することができるので、Storybookによってtitleタグが変更された直後に書き換えを行います。

ページ名が設定されるのは活かして、「Storybook」という文言のみ置き換えました。

new MutationObserver(records => {
  // 自分で書き換えたときも検知されてしまうので、無限ループにならないよう気を付けましょう
  if (document.title.includes('Storybook')) {
    document.title = document.title.replace('Storybook', 'サイト名')
  }
}).observe(document.querySelector('title'), { childList: true })

こちらのscriptを.storybook/manager-head.htmlあたりに書き込みます。

faviconを設定

  1. public/favicon.icoにアイコンを置きます。
  2. .storybook/manager-head.htmlにfavicon.icoの読み込みタグを足します。
  3. 初期レンダリング時のtitleタグを変更』と同様の手順で元々存在するfavicon読み込みタグを削除します。

おわりに

Storybook、できあがるものは素晴らしんですが、色々カスタマイズしようとしたときの設定やらが難解すぎてキレそう。

3
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
3
0