Skip to main content

スウィズリング(Swizzling)

ここでは、Docusaurusでレイアウトをカスタマイズする方法を紹介します。

見覚えがあるような……?

このセクションはスタイリングとレイアウトと似ていますが、今回はReactコンポーネントの見た目ではなく、コンポーネントそのものをカスタマイズします。 Docusaurusの中心的な概念であるスウィズリングについて説明します。これにより、より高度なサイトのカスタマイズが可能になります。

実際には、スウィズリングはテーマのコンポーネントを自分の実装と入れ替えることを許可するもので、以下の2種類に分けられます。

スウィズリングと呼ばれている理由

この名前はObjective-C及びSwift-UIに由来しています。メソッドのスウィズリングとは、既存のセレクタ(メソッド)の実装を変更する処理のことを言います。

Docusaurusでは、コンポーネントのスウィズリングはテーマが提供するコンポーネントよりも優先される代替コンポーネントを提供することを意味します。

Reactコンポーネントのモンキーパッチと同じようなもので、既定の実装を上書きすることができます。 Gatsbyには、テーマのシャドーイングという同様の概念があります。

これをより詳しく理解するためには、テーマの構成要素がどのように解決されるかを理解しておく必要があります。

スウィズリングの過程

概要

Docusaurusは、コンポーネントをスウィズリングするための便利な対話式のCLIを用意しています。 通常は、次のコマンドだけ覚えておけば十分です。

npm run swizzle

これにより、src/themeディレクトリに次の例のような新しいコンポーネントが生成されます。

src/theme/SomeComponent.js
import React from 'react';

export default function SomeComponent(props) {
// JSX・CSS・React hooksの変更を含め、
// この実装を完全にカスタマイズできます
return (
<div className="some-class">
<h1>コンポーネント</h1>
<p>コンポーネントの実装詳細</p>
</div>
);
}

スウィズリング可能な全てのテーマとコンポーネントの概要を把握するには、次のコマンドを実行してください。

npm run swizzle -- --list

--helpで全ての利用可能なコマンドオプションを確認するか、swizzleサブコマンドのドキュメンテーションリファレンスを参照してください。

メモ

コンポーネントをスウィズリングしたら、Docusaurusに新しいコンポーネントを認識させるため、開発サーバを再起動してください。

安全策を取るようにすること

どのコンポーネントがスウィズリングしても安全なのかを必ず理解しておきましょう。 一部のコンポーネントは、テーマの内部実装の詳細部分です。

情報

docusaurus swizzleは、コンポーネントのスウィズリングを支援する自動化された手段にすぎません。 src/theme/SomeComponent.jsファイルを手動で作成することもでき、Docusaurusは それを解決します。 このコマンドの内部に隠れている魔法があるわけではありません!

取り出し(Ejecting)

Ejecting a theme component is the process of creating a copy of the original theme component, which you can fully customize and override.

To eject a theme component, use the swizzle CLI interactively, or with the --eject option:

npm run swizzle [テーマ名] [コンポーネント名] -- --eject

例:

npm run swizzle @docusaurus/theme-classic Footer -- --eject

This will copy the current <Footer /> component's implementation to your site's src/theme directory. Docusaurus will now use this <Footer> component copy instead of the original one. You are now free to completely re-implement the <Footer> component.

src/theme/Footer/index.js
import React from 'react';

export default function Footer(props) {
return (
<footer>
<h1>This is my custom site footer</h1>
<p>And it is very different from the original</p>
</footer>
);
}
警告

Ejecting an unsafe component can sometimes lead to copying a large amount of internal code, which you now have to maintain yourself. It can make Docusaurus upgrades more difficult, as you will need to migrate your customizations if the props received or internal theme APIs used have changed.

Prefer wrapping whenever possible: the amount of code to maintain is smaller.

Re-swizzling

To keep ejected components up-to-date after a Docusaurus upgrade, re-run the eject command and compare the changes with git diff. You are also recommended to write a brief comment at the top of the file explaining what changes you have made, so that you could more easily re-apply your changes after re-ejection.

ラッピング(Wrapping)

Wrapping a theme component is the process of creating a wrapper around the original theme component, which you can enhance.

To wrap a theme component, use the swizzle CLI interactively, or with the --wrap option:

npm run swizzle [テーマ名] [コンポーネント名] -- --wrap

例:

npm run swizzle @docusaurus/theme-classic Footer -- --wrap

This will create a wrapper in your site's src/theme directory. Docusaurus will now use the <FooterWrapper> component instead of the original one. You can now add customizations around the original component.

src/theme/Footer/index.js
import React from 'react';
import Footer from '@theme-original/Footer';

export default function FooterWrapper(props) {
return (
<>
<section>
<h2>Extra section</h2>
<p>This is an extra section that appears above the original footer</p>
</section>
<Footer {...props} />
</>
);
}
What is this @theme-original thing?

Docusaurus uses theme aliases to resolve the theme components to use. The newly created wrapper takes the @theme/SomeComponent alias. @theme-original/SomeComponent permits to import original component that the wrapper shadows without creating an infinite import loop where the wrapper imports itself.

ヒント

Wrapping a theme is a great way to add extra components around existing one without ejecting it. For example, you can easily add a custom comment system under each blog post:

src/theme/BlogPostItem.js
import React from 'react';
import BlogPostItem from '@theme-original/BlogPostItem';
import MyCustomCommentSystem from '@site/src/MyCustomCommentSystem';

export default function BlogPostItemWrapper(props) {
return (
<>
<BlogPostItem {...props} />
<MyCustomCommentSystem />
</>
);
}

スウィズリングしても安全なもの

大いなる力には、大いなる責任を伴う

一部のテーマコンポーネントは、テーマの内部実装の詳細です。 Docusaurusではそれらのスウィズリングもできるようにしていますが、これは危険な場合があります。

危険な理由

Theme authors (including us) might have to update their theme over time: changing the component props, name, file system location, types... For example, consider a component that receives two props name and age, but after a refactor, it now receives a person prop with the above two properties. Your component, which still expects these two props, will render undefined instead.

Moreover, internal components may simply disappear. If a component is called Sidebar and it's later renamed to DocSidebar, your swizzled component will be completely ignored.

Theme components marked as unsafe may change in a backward-incompatible way between theme minor versions. When upgrading a theme (or Docusaurus), your customizations might behave unexpectedly, and can even break your site.

For each theme component, the swizzle CLI will indicate 3 different levels of safety declared by theme authors:

  • Safe: this component is safe to be swizzled, its public API is considered stable, and no breaking changes should happen within a theme major version
  • Unsafe: this component is a theme implementation detail, not safe to be swizzled, and breaking changes might happen within a theme minor version
  • Forbidden: the swizzle CLI will prevent you from swizzling this component, because it is not designed to be swizzled at all
メモ

Some components might be safe to wrap, but not safe to eject.

情報

Don't be too afraid to swizzle unsafe components: just keep in mind that breaking changes might happen, and you might need to upgrade your customizations manually on minor version upgrades.

Report your use-case

If you have a strong use-case for swizzling an unsafe component, please report it here and we will work together to find a solution to make it safe.

どのコンポーネントをスウィズリングすべきか

It is not always clear which component you should swizzle exactly to achieve the desired result. @docusaurus/theme-classic, which provides most of the theme components, has about 100 components!

ヒント

To print an overview of all the @docusaurus/theme-classic components:

npm run swizzle @docusaurus/theme-classic -- --list

You can follow these steps to locate the appropriate component to swizzle:

  1. Component description. Some components provide a short description, which is a good way to find the right one.
  2. Component name. Official theme components are semantically named, so you should be able to infer its function from the name. The swizzle CLI allows you to enter part of a component name to narrow down the available choices. For example, if you run yarn swizzle @docusaurus/theme-classic, and enter Doc, only the docs-related components will be listed.
  3. Start with a higher-level component. Components form a tree with some components importing others. Every route will be associated with one top-level component that the route will render (most of them listed in Routing in content plugins). For example, all blog post pages have @theme/BlogPostPage as the topmost component. You can start with swizzling this component, and then go down the component tree to locate the component that renders just what you are targeting. Don't forget to unswizzle the rest by deleting the files after you've found the correct one, so you don't maintain too many components.
  4. Read the theme source code and use search wisely.
Just ask!

If you still have no idea which component to swizzle to achieve the desired effect, you can reach out for help in one of our support channels.

We also want to understand better your fanciest customization use-cases, so please report them.

スウィズリングを行う必要があるか

Swizzling ultimately means you have to maintain some additional React code that interact with Docusaurus internal APIs. If you can, think about the following alternatives when customizing your site:

  1. Use CSS. CSS rules and selectors can often help you achieve a decent degree of customization. Refer to styling and layout for more details.
  2. Use translations. It may sound surprising, but translations are ultimately just a way to customize the text labels. For example, if your site's default language is en, you can still run yarn write-translations -l en and edit the code.json emitted. Refer to the i18n tutorial for more details.
ヒント

The smaller, the better. If swizzling is inevitable, prefer to swizzle only the relevant part and maintain as little code on your own as possible. Swizzling a small component often means less risk of breaking changes during upgrade.

Wrapping is also a far safer alternative to ejecting.

サイトを<Root>でくるむ

The <Root> component is rendered at the very top of the React tree, above the theme <Layout>, and never unmounts. It is the perfect place to add stateful logic that should not be re-initialized across navigations (user authentication status, shopping cart state...).

Swizzle it manually by creating a file at src/theme/Root.js:

src/theme/Root.js
import React from 'react';

// デフォルト実装(カスタマイズして構いません)
export default function Root({children}) {
return <>{children}</>;
}
ヒント

React Contextプロバイダをレンダリングするには、このコンポーネントを使用してください。