Skip to main content

Customizing Docusaurus Theme Everywhere with Swizzling

1. Background

Whether it is Adding a Comment System to Docusaurus or Docusaurus Customize 404 Page

Actually, both use the Docusaurus Swizzling feature. I specifically looked through the official Docusaurus documentation, and there is actually a very detailed explanation of this, which facilitates our customization of Docusaurus.

Original documentation link: Swizzling

2. Swizzling

By Swizzling, we will customize the React components themselves, not their appearance. We will discuss a core concept in Docusaurus: swizzling, which allows for deeper website customization.

In practice, swizzling allows you to swap theme components with your own implementation. It has two modes:

Ejecting: Creates a copy of the original theme component, which you can fully customize. Wrapping: Creates a wrapper around the original theme component, which you can enhance.

3. Swizzling Process

3.1 Overview

Docusaurus provides a convenient interactive CLI to transform components. Usually, you just need to remember the following command:

npm run swizzle

It will generate a new component in your src/theme directory, which looks like the example below:

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

export default function SomeComponent(props) {
// You can fully customize this implementation
// Including changing JSX, CSS, and React hooks
return (
<div className="some-class">
<h1>Some Component</h1>
<p>Some component implementation details</p>
</div>
);
}

To view all available themes and components for swizzling, run

npm run swizzle -- --list

Use --help to view all available CLI options, or refer to the swizzle CLI reference documentation.

Delete Unwanted Swizzled Components

If you decide you no longer need a previously swizzled component, just delete its file from the src/theme directory. After deleting the component, make sure to restart the server to ensure the changes are correctly reflected.

Remark

After swizzling a component, please restart the development server so that Docusaurus refreshes the new component.

Better safe than sorry

Be sure to understand which components are safe to use. Some components are internal implementation details of the theme.

Delete Unwanted Swizzled Components

docusaurus swizzle is just a way to help you automatically adjust components. You can also manually create the src/theme/SomeComponent.js file, and Docusaurus will automatically resolve it. There is no internal magic behind this command!

3.2 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 interactive operation or the --eject option:

npm run swizzle [theme name] [component name] -- --eject

An example:

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