Skip to main content

6 posts tagged with "Docusaurus"

View All Tags

· 2 min read
wen

前言

Docusaurus 是一个由 Facebook 开发的开源项目,用于构建静态网站。

它是一个基于 React 的静态网站生成器,可以帮助您快速创建网站。

Docusaurus 还提供了一个易于使用的博客插件,可以帮助您创建博客。

Docusaurus 默认不提供 RSS 导航菜单,在本文中,我们将介绍如何为 Docusaurus 博客添加 RSS 导航菜单。

怎么给 Docusaurus 博客 添加 RSS 导航菜单

docusaurus.config.js
module.exports = {
...
themeConfig: {
...
navbar: {
items: [
// blog rss
{
href: '/blog/rss.xml',
label: 'RSS',
position: 'right',
target: '_blank', // Open the link in a new tab/window
},
],
...

补充说明

BTW, 如果用 to 选项的话,点击 RSS 链接会报页面无法找到的 404 错误,

因为 Docusaurus 会把 to 选项的值当作一个页面的路径,而不是一个链接。

docusaurus.config.js
module.exports = {
...
themeConfig: {
...
navbar: {
items: [
// blog rss
{
to: '/blog/rss.xml',
label: 'RSS',
position: 'right',
},
],
...

· One min read
wen

Problem

Docusaurus(3.0) 的文档侧边栏默认是按文件的创建日期的升序排列的。

Docuaurus v3 's docs sidebar is sorted by the creation date of the file by default.

It's not very convenient for me to manage and find docs, so I want to reverse the order of the sidebar items.

img

Solution

Modify the docusaurus.config.js file as follows:

docusaurus.config.js
+// Reverse the sidebar items ordering (including nested category items)
+function reverseSidebarItems(items) {
+ // Reverse items in categories
+ const result = items.map((item) => {
+ if (item.type === 'category') {
+ return {...item, items: reverseSidebarItems(item.items)};
+ }
+ return item;
+ });
+ // Reverse items at current level
+ result.reverse();
+ return result;
+}

/** @type {import('@docusaurus/types').Config} */
const config = {
title: 'thewang',
...
presets: [
[
'classic',
/** @type {import('@docusaurus/preset-classic').Options} */
({
docs: {
routeBasePath: 'weekly',
sidebarPath: require.resolve('./sidebars.js'),
showLastUpdateTime: true,
showLastUpdateAuthor: true,
sidebarCollapsed: false,
+ async sidebarItemsGenerator({defaultSidebarItemsGenerator, ...args}) {
+ const sidebarItems = await defaultSidebarItemsGenerator(args);
+ return reverseSidebarItems(sidebarItems);
+ return sidebarItems;
+ },
},
...

References

Customize the sidebar items generator

· 2 min read
wen

问题

Docuaurus 的文档(Docs)默认的 URL 路径名是 /docs,如:https://thewang.net/docs

如果你想把它改成 /api,如:https://thewang.net/api ,该怎么做呢?

解决方法

docusaurus.config.js 中,

  • 找到 docs 的配置项,添加 routeBasePath 属性,值为你想要的 URL 路径名,如:api
  • 找到 navbar 的配置项,
docusaurus.config.js
  presets: [
[
'classic',
/** @type {import('@docusaurus/preset-classic').Options} */
({
docs: {
+ routeBasePath: 'api',
sidebarPath: require.resolve('./sidebars.js'),
...
docusaurus.config.js
     navbar: {
...
items: [
{ to: '/blog', label: 'Blog', position: 'left' },
// API docs
{
to: '/api',
type: 'docSidebar',
label: 'API',
...
},

补充

那那些已经公开的文档(Docs)的 URL 路径不能访问了該怎么办呢?

可以安装 docusaurus/plugin-client-redirects 插件,来实现重定向解决。

  npm install @docusaurus/[email protected] // 注意和你的 docusaurus 版本对应
docusaurus.config.js
...
+ plugins: [
+ [
+ '@docusaurus/plugin-client-redirects',
+ {
+ createRedirects(existingPath) {
+ if (existingPath.includes('/api')) {
+ // Redirect from /docs to /weekly
+ return [
+ existingPath.replace('/api', '/docs'),
+ ];
+ }
+ return undefined; // Return a falsy value: no redirect created
+ },
+ },
+ ]
+ ],

presets: [
...
PRODUCTION ONLY

This plugin is always inactive in development and only active in production because it works on the build output.

@docusaurus/plugin-client-redirects 只在生产环境下生效。

· 5 min read
wen

背景

Docusaurus 默认没有集成评论系统。

在之前的博客中用过 Giscus ,

它是一个基于 GitHub Discussions 的评论系统,可以很方便地集成到 GitHub Pages、VuePress、Docusaurus 等静态网站生成器中。

这次打算把它添加到 Docusaurus。

tip

如果不想依存 Github 的服务,可以开卡 Waline 评论系统,可以添加自己的后端服务。

准备工作

tip

可以点击流程图中带下划线的 node 跳转到相关页面

步骤

  • 流程图

1. 配置 Giscus

Giscus 的网站上配置你的评论系统,并复制你的配置代码(高亮部分会在步骤 3 中用到)。

giscus config
<script src="https://giscus.app/client.js"
data-repo="your_org_name/your-repo"
data-repo-id="your-repo-id"
data-category="Announcements"
data-category-id="your-category-id"
... // other options
async>
</script>

2. 创建评论组件

2.1. 安装依赖

npm install @giscus/react mitt

# or
yarn add @giscus/react mitt

2.2. 创建组件

点击查看代码
src/components/GiscusComments/index.tsx
import React from "react";
import { useThemeConfig, useColorMode } from "@docusaurus/theme-common";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
import { ThemeConfig } from "@docusaurus/preset-classic";
import BrowserOnly from "@docusaurus/BrowserOnly";
import Giscus, { GiscusProps } from "@giscus/react";

interface CustomThemeConfig extends ThemeConfig {
giscus: GiscusProps & { darkTheme: string };
}

const defaultConfig: Partial<GiscusProps> & { darkTheme: string } = {
id: "comments",
mapping: "title",
reactionsEnabled: "1",
emitMetadata: "0",
inputPosition: "top",
lang: "zh-CN",
theme: "light",
darkTheme: "dark",
};

export default function Comment(): JSX.Element {
const themeConfig = useThemeConfig() as CustomThemeConfig;
const { i18n } = useDocusaurusContext();

// merge default config
const giscus = { ...defaultConfig, ...themeConfig.giscus };

if (!giscus.repo || !giscus.repoId || !giscus.categoryId) {
throw new Error(
"You must provide `repo`, `repoId`, and `categoryId` to `themeConfig.giscus`."
);
}

giscus.theme =
useColorMode().colorMode === "dark" ? giscus.darkTheme : giscus.theme;
giscus.lang = i18n.currentLocale;

return (
<BrowserOnly fallback={<div>Loading Comments...</div>}>
{() => <Giscus {...giscus} />}
</BrowserOnly>
);
}

用 Docusaurus 的 swizzle 命令对博客页面对应组件进行修改(添加前面创建的评论组件)。

npm run swizzle @docusaurus/theme-classic BlogPostPage -- --eject --typescript
# or
yarn run swizzle @docusaurus/theme-classic BlogPostPage -- --eject --typescript

以上命令会在 src/theme/BlogPostPage/index.tsx 中生成一些文件,我们只需要修改 index.tsx 文件即可。

以下高亮部分为修改代码:

点击查看代码
src/theme/BlogPostPage/index.tsx
import React, {type ReactNode} from 'react';
import clsx from 'clsx';
import {HtmlClassNameProvider, ThemeClassNames} from '@docusaurus/theme-common';
import {BlogPostProvider, useBlogPost} from '@docusaurus/theme-common/internal';
import BlogLayout from '@theme/BlogLayout';
import BlogPostItem from '@theme/BlogPostItem';
import BlogPostPaginator from '@theme/BlogPostPaginator';
import BlogPostPageMetadata from '@theme/BlogPostPage/Metadata';
import TOC from '@theme/TOC';
import type {Props} from '@theme/BlogPostPage';
import Unlisted from '@theme/Unlisted';
import type {BlogSidebar} from '@docusaurus/plugin-content-blog';
import Comment from '../../components/GiscusComments';

function BlogPostPageContent({
sidebar,
children,
}: {
sidebar: BlogSidebar;
children: ReactNode;
}): JSX.Element {
const {metadata, toc} = useBlogPost();
const {nextItem, prevItem, frontMatter, unlisted} = metadata;
const {
hide_table_of_contents: hideTableOfContents,
toc_min_heading_level: tocMinHeadingLevel,
toc_max_heading_level: tocMaxHeadingLevel,
hide_comment: hideComment,
} = frontMatter;
return (
<BlogLayout
sidebar={sidebar}
toc={
!hideTableOfContents && toc.length > 0 ? (
<TOC
toc={toc}
minHeadingLevel={tocMinHeadingLevel}
maxHeadingLevel={tocMaxHeadingLevel}
/>
) : undefined
}>
{unlisted && <Unlisted />}
<BlogPostItem>{children}</BlogPostItem>

{(nextItem || prevItem) && (
<BlogPostPaginator nextItem={nextItem} prevItem={prevItem} />
)}
{!hideComment && <Comment />}
</BlogLayout>
);
}

...

2.3. 配置 Docusaurus

docusaurus.config.js 中添加配置项:

docusaurus.config.js
module.exports = {
...
themeConfig: {
...
// giscus options
giscus: {
repo: 'your_org/your-blog', // edit this
repoId: 'your_repo_id', // edit this
category: 'Announcements',
categoryId: 'your_category_id', // edit this
}
...
},
...
}

3. 重启 Docusaurus

npm start
# or
yarn start

参考

Docusaurus 添加评论功能

评论服务

· One min read
wen

背景

当你的博客文章越来越多时,你可能会发现你的博客需要一个 tags 菜单,以便用户可以快速找到他们感兴趣的文章。

本文将介绍如何为 Docusaurus 博客添加 tags 菜单。

img

添加 tags 菜单

只需要在 docusaurus.config.js 配置文件中,添加如下配置即可:

docusaurus.config.js
      navbar: {
title: 'thewang',
logo: {
alt: 'thewang logo',
src: 'img/logo.png',
},
items: [
{ to: '/blog', label: 'Blog', position: 'left' },
// language dropdown menu
{
type: 'localeDropdown',
position: 'right',
},
...
// tags menu
{
to: '/blog/tags',
label: 'Tags',
position: 'left',
},

· 2 min read
wen

Update Docusaurus to v3

Docuaurus v3 has been released, here is the migration guide provided by the official.

I record the upgrade process here that may help you save some time. 😄

Upgrade dependencies

  • docusaurus.config.js
docusaurus.config.js

-const lightCodeTheme = require('prism-react-renderer/themes/github');
-const darkCodeTheme = require('prism-react-renderer/themes/dracula');
+const { themes } = require('prism-react-renderer');
+const lightTheme = themes.github;
+const darkTheme = themes.dracula;

prism: {
- theme: lightCodeTheme,
- darkTheme: darkCodeTheme,
+ theme: lightTheme,
+ darkTheme: darkTheme,
},

  • package.json
package.json
   "dependencies": {
- "@docusaurus/core": "2.4.3",
- "@docusaurus/preset-classic": "2.4.3",
- "@docusaurus/theme-mermaid": "^2.4.3",
- "@mdx-js/react": "^1.6.22",
+ "@docusaurus/core": "3.0.0",
+ "@docusaurus/preset-classic": "3.0.0",
+ "@docusaurus/theme-mermaid": "^3.0.0",
+ "@mdx-js/react": "^3.0.0",
"clsx": "^1.2.1",
- "prism-react-renderer": "^1.3.5",
- "react": "^17.0.2",
- "react-dom": "^17.0.2"
+ "prism-react-renderer": "^2.1.0",
+ "react": "^18.2.0",
+ "react-dom": "^18.2.0"
},
"devDependencies": {
- "@docusaurus/module-type-aliases": "2.4.3"
+ "@docusaurus/module-type-aliases": "3.0.0",
+ "@docusaurus/types": "3.0.0"
},


"engines": {
- "node": ">=16.14"
+ "node": ">=18.0"
}

Reinstall dependencies

Remove the node_modules directory and package-lock.json file, then reinstall the dependencies.

npm install

Check if mx/mdx files compiles under MDX v3

Use the following command to check if mx/mdx files compiles under MDX v3.

npx docusaurus-mdx-checker

For example, I got a check error after upgrated to v3:

  • Before Modified
<details><summary>xxx</summary>
...
</details>
  • After Modified
<details>
<summary>xxx</summary>
...
</details>