Swizzle
在本节中,我们将介绍如何在 Docusaurus 中完成自定义布局。
似曾相识?
This section is similar to Styling and Layout, but this time, we will customize React components themselves, rather than what they look like. We will talk about a central concept in Docusaurus: swizzling, which allows deeper site customizations.
In practice, swizzling permits to swap a theme component with your own implementation, and it comes in 2 patterns:
- 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
Why is it called swizzling?
The name comes from Objective-C and Swift-UI: method swizzling is the process of changing the implementation of an existing selector (method).
For Docusaurus, component swizzling means providing an alternative component that takes precedence over the component provided by the theme.
You can think of it as Monkey Patching for React components, enabling you to override the default implementation. Gatsby has a similar concept called theme shadowing.
To gain a deeper understanding of this, you have to understand how theme components are resolved.
Swizzle 的过程
概览
Docusaurus provides a convenient interactive CLI to swizzle components. 你一般只需要记住以下指令:
- npm
- Yarn
- pnpm
npm run swizzle
yarn swizzle
pnpm run swizzle
It will generate a new component in your src/theme
directory, which should look like this example:
- Ejecting
- Wrapping
import React from 'react';
export default function SomeComponent(props) {
// You can fully customize this implementation
// including changing the JSX, CSS and React hooks
return (
<div className="some-class">
<h1>Some Component</h1>
<p>Some component implementation details</p>
</div>
);
}
import React from 'react';
import SomeComponent from '@theme-original/SomeComponent';
export default function SomeComponentWrapper(props) {
// You can enhance the original component,
// including adding extra props or JSX elements around it
return (
<>
<SomeComponent {...props} />
</>
);
}
要总览所有可用的主题和组件,请运行:
- npm
- Yarn
- pnpm
npm run swizzle -- --list