サイト全体のレイアウトをカスタマイズ
そこそこ大変
ファイルもたくさん(と感じる程度に)生成されるし、
コマンドは「ほんとにやるの?」みたいな警告を出すし、
みんな index.tsx なので途中でどこ触ってるか分からなくなるしで、
慣れてきてからやるべきだったかもしれない。。
とはいえ
もとに戻すには生成されたものをディレクトリごと消すだけなので、
試したいなら試せばよいし、仕組みとしては分かりやすい。
やりたいこと
- 画面下部に広告用の領域を確保
- そこに Google AdSense を埋め込む
- ただし PC 版のみ表示 (モバイル版は 画面下部ではなくて、各コンテンツに埋め込んでいるため)
テンプレート生成 (Swizzle)
3箇所いじることになる。
- サイト全体のレイアウト
- ページのレイアウト
- Sidebar のレイアウト
1. サイト全体のレイアウト
bash
npx docusaurus swizzle @docusaurus/theme-classic Layout
→ src/theme/Layout/index.tsx
が作成される
カスタマイズ箇所をゴリゴリのまま記載しておく。
tsx
const location = useLocation();
const isMobile = useMediaQuery({ maxWidth: 767 });
// ✓ 広告用に追加
useEffect(() => {
// if (isMobile) return; // どちらでも push する
try {
(window.adsbygoogle = window.adsbygoogle || []).push({});
} catch (e) {
console.warn('AdSense push failed:', e);
}
// }, [location.pathname, isMobile]); // ← ページ遷移もトリガにする
}, [location.pathname]); // ← ページ遷移時のみトリガにする
tsx
{/* ★下部に固定する領域 */}
{!isMobile && (
<div
key={location.pathname}
style={{
position: 'fixed',
bottom: 0,
left: 0,
width: '100%',
height: '100px',
backgroundColor: '#eee',
zIndex: 1000,
textAlign: 'center',
}}
>
<ins
key={location.pathname}
className="adsbygoogle"
style={{ display: 'block', minHeight: '100px' }}
data-ad-client="ca-pub-XXXXXXXXXXXX"
data-ad-slot="XXXXXXXXX"
data-ad-format="landscape"
data-full-width-responsive="true"
/>
</div>
)}
2. ページのレイアウト
bash
npx docusaurus swizzle @docusaurus/theme-classic DocItem/Layout
→ src/theme/DocItem/Layout/index.tsx
が作成される
tsx
<div className={styles.docItemContainer}>
↓
<div className={styles.docItemContainer} style={{ paddingBottom: '100px' }}>
★ 追加
3. Sidebar のレイアウト
bash
npx docusaurus swizzle @docusaurus/theme-classic DocSidebar
→ src/theme/DocSidebar/index.tsx
src/theme/DocSidebar/Desktop/index.tsx
が作成される
デスクトップだけ対応する
src/theme/DocSidebar/Desktop/index.tsx
<div
className={clsx(
styles.sidebar,
hideOnScroll && styles.sidebarWithHideableNavbar,
isHidden && styles.sidebarHidden,
)}
style={{ paddingBottom: '100px' }} // ← ★ 追加
>