スマレジエンジニアyushiのブログ

スマレジエンジニアのブログ

【自作ブログ #15】GitHub Pagesでの公開(2)

自作ブログを作っています。

yushi-dev.hatenablog.com

技術スタック

  • TypeScript
  • React
  • Next.js
  • Styled Components
  • GitHub Pages

今回はGitHub Pagesでの公開のための修正などをしていきます。

画像が表示されない問題

前回も言及した通りですが、GitHub Pagesの場合パスが下記のようになります。

https://[user-name].github.io/[repository-name]

このために、GitHub Pages上で画像が表示されない問題が発生してしまいました。

この解決のため、URLにbasePathを付与するメソッドを作成しました。

まず、next.config.js にbasePathを登録します。

const basePath = process.env.BASE_PATH ? '/' + process.env.BASE_PATH : ''

const nextConfig = {
  publicRuntimeConfig: {
    basePath,
  },
}

この設定値を利用するメソッドは下記です。

import getConfig from 'next/config'

export function url(path: string): string {
  const { publicRuntimeConfig } = getConfig() as {
    publicRuntimeConfig: { basePath: string }
  }

  return publicRuntimeConfig.basePath + path
}

最後に、これを利用した画像が表示できるように修正します。

(pages/index.tsx)

import { url } from '@/utils/config-utils'

const heroBackgroundImageUrl = url('/hero.jpg')

const HeroContainer = styled(Container)`
  height: 400px;
  margin: 0 auto;
  - background-image: url('/hero.jpg');
  + background-image: url(${heroBackgroundImageUrl});
  background-position: center;
  background-size: cover;
`
(SideMenu.tsx)

<StyleImage
  layout="fixed"
  - src="/profile.png"
  + src={url('/profile.png')}
  alt="profile image"
  width={imageSize}
  height={imageSize}
/>

リンクが正しくない問題

同様に、リンクが正しくない問題があります。

https://nek0meshi.github.io/posts/sample2

となっていますが、正しくは下記です。

https://nek0meshi.github.io/blog/posts/sample2

こちらの問題は、単に next/Link を利用することで修正できました。

const TopNav = ({ text, href }: Props) => {
  - return <A href={href}>{text}</A>
  + return (
  +   <Link href={href} passHref>
  +     <A>{text}</A>
  +   </Link>
  + )
}

スクリーンショット

Pull Request

https://github.com/nek0meshi/blog/pull/17

あとがき

またしても体調を崩してしまいました...。

体を強くしたいです。