跳到主要内容

📦 plugin-content-blog

提供 博客 功能,是道格龙(Docusaurus)默认的博客插件。

部分功能仅在生产环境可用

Feed 功能 通过提取构建产物实现,仅在生产环境下生效

安装

npm install --save @docusaurus/plugin-content-blog
提示

如果你使用了 @docusaurus/preset-classic 预设,则无需单独安装此插件。

你可以通过 预设选项 配置此插件。

配置

可用字段:

名称类型默认值说明
pathstring'blog'博客内容目录在文件系统中的路径,相对于站点目录。
editUrlstring | EditUrlFnundefined编辑站点的基础 URL。最终 URL 由 editUrl + relativePostPath 计算得出。使用函数可为每个文件实现更灵活的控制。完全省略该变量将禁用编辑链接。
editLocalizedFilesbooleanfalse编辑 URL 将指向本地化文件,而不是原始未本地化文件。当 editUrl 为函数时忽略此项。
blogTitlestring'Blog'博客页面标题,有助于 SEO。
blogDescriptionstring'Blog'博客页面的 meta 描述,有助于 SEO。
blogSidebarCountnumber | 'ALL'5博客侧边栏显示的文章数量。'ALL' 显示全部,0 表示不显示。
blogSidebarTitlestring'Recent posts'博客侧边栏标题。
routeBasePathstring'blog'博客部分的 URL 路由。不要包含结尾斜杠。使用 / 可让博客位于根路径。
tagsBasePathstring'tags'博客标签部分的 URL 路由,会被加在 routeBasePath 后面。
pageBasePathstring'page'博客页面部分的 URL 路由,会被加在 routeBasePath 后面。
archiveBasePathstring | null'archive'博客归档部分的 URL 路由,会被加在 routeBasePath 后面。不要包含结尾斜杠。设为 null 可禁用归档生成。
authorsBasePathstring'authors'博客作者页面的 URL 路由,会被加在 path 后面。
includestring[]['**/*.{md,mdx}']匹配需要构建的 Markdown 文件的 glob 模式数组,相对于内容路径。
excludestring[]见示例配置匹配需要排除的 Markdown 文件的 glob 模式数组。作为 include 选项的补充。
postsPerPagenumber | 'ALL'10博客列表页每页显示的文章数。'ALL' 表示全部显示在一页。
blogListComponentstring'@theme/BlogListPage'博客列表页的根组件。
blogPostComponentstring'@theme/BlogPostPage'每篇博客文章页面的根组件。
blogTagsListComponentstring'@theme/BlogTagsListPage'标签列表页的根组件。
blogTagsPostsComponentstring'@theme/BlogTagsPostsPage'"包含标签的文章"页面的根组件。
blogArchiveComponentstring'@theme/BlogArchivePage'博客归档页的根组件。
blogAuthorsPostsComponentstring'@theme/Blog/Pages/BlogAuthorsPostsPage'博客作者页面的根组件。
blogAuthorsListComponentstring'@theme/Blog/Pages/BlogAuthorsListPage'博客作者索引页的根组件。
remarkPluginsany[][]传递给 MDX 的 Remark 插件。
rehypePluginsany[][]传递给 MDX 的 Rehype 插件。
rehypePluginsany[][]传递给 MDX 的 Recma 插件。
beforeDefaultRemarkPluginsany[][]在默认道格龙 Remark 插件之前传递给 MDX 的自定义 Remark 插件。
beforeDefaultRehypePluginsany[][]在默认道格龙 Rehype 插件之前传递给 MDX 的自定义 Rehype 插件。
truncateMarkerRegExp/<!--\s*truncate\s*-->/ | {/*\s*truncate\s**/}用于标记摘要结束位置的截断标记。
showReadingTimebooleantrue是否显示博客文章的预计阅读时间。
readingTimeReadingTimeFn默认阅读时间用于自定义显示阅读时间的回调函数。
authorsMapPathstring'authors.yml'作者映射文件的路径,相对于博客内容目录。
feedOptions见下方{type: ['rss', 'atom']}博客 Feed 配置。
feedOptions.typeFeedType | FeedType[] | 'all' | null必填要生成的 Feed 类型。设为 null 可禁用生成。
feedOptions.createFeedItemsCreateFeedItemsFn | undefinedundefined可选函数,用于转换和/或过滤 Feed 中的条目。
feedOptions.limitnumber | null | false20Feed 中最多包含的文章数,falsenull 表示全部,默认 20。
feedOptions.titlestringsiteConfig.titleFeed 标题。
feedOptions.descriptionstring${siteConfig.title} BlogFeed 描述。
feedOptions.copyrightstringundefined版权信息。
feedOptions.xsltboolean | FeedXSLTOptionsundefined允许用 XSLT 美化博客 XML Feed,使浏览器友好显示。
feedOptions.languagestringundefinedFeed 的语言元数据。
sortPosts'descending' | 'ascending' 'descending'博客文章排序方向。
processBlogPostsProcessBlogPostsFnundefined可选函数,用于转换博客文章(过滤、修改、删除等)。
showLastUpdateAuthorbooleanfalse是否显示博客文章最后更新作者。
showLastUpdateTimebooleanfalse是否显示博客文章最后更新时间。此功能需要在构建时访问 git 历史,因此在浅克隆(CI 系统常见默认设置)下无法正常工作。使用 GitHub actions/checkout 时需设置 fetch-depth: 0
tagsstring | false | null | undefinedtags.yml预定义标签的 YAML 文件路径。相对于博客内容目录。
onInlineTags'ignore' | 'log' | 'warn' | 'throw'warn当博客文章包含内联标签(未出现在预定义标签列表中,通常为 tags.yml)时插件的行为。
onUntruncatedBlogPosts'ignore' | 'log' | 'warn' | 'throw'warn当博客文章未包含截断标记时插件的行为。

类型定义

EditUrlFn

type EditUrlFunction = (params: {
blogDirPath: string;
blogPath: string;
permalink: string;
locale: string;
}) => string | undefined;

ReadingTimeFn

type ReadingTimeOptions = {
wordsPerMinute: number;
};

type ReadingTimeCalculator = (params: {
content: string;
locale: string;
frontMatter?: BlogPostFrontMatter & Record<string, unknown>;
options?: ReadingTimeOptions;
}) => number;

type ReadingTimeFn = (params: {
content: string;
locale: string;
frontMatter: BlogPostFrontMatter & Record<string, unknown>;
defaultReadingTime: ReadingTimeCalculator;
}) => number | undefined;

FeedType

type FeedType = 'rss' | 'atom' | 'json';

FeedXSLTOptions

允许用 XSLT 美化博客 XML Feed,使浏览器友好显示。

  • 使用 true 让博客使用内置的 .xsl.css 文件美化 Feed
  • 使用假值(undefined | null | false)禁用该功能
  • 使用 string 指定自定义 .xsl 文件路径(相对于博客内容文件夹)。约定需提供同名 .css 文件。
type FeedXSLTOptions =
| boolean
| undefined
| null
| {
rss?: string | boolean | null | undefined;
atom?: string | boolean | null | undefined;
};

CreateFeedItemsFn

type CreateFeedItemsFn = (params: {
blogPosts: BlogPost[];
siteConfig: DocusaurusConfig;
outDir: string;
defaultCreateFeedItemsFn: CreateFeedItemsFn;
}) => Promise<BlogFeedItem[]>;

ProcessBlogPostsFn

type ProcessBlogPostsFn = (params: {
blogPosts: BlogPost[];
}) => Promise<void | BlogPost[]>;

示例配置

你可以通过预设选项或插件选项配置此插件。

提示

大多数道格龙用户通过预设选项配置此插件。

// 预设选项:blog
// 插件选项:@docusaurus/plugin-content-blog

const config = {
path: 'blog',
// 简单用法:字符串 editUrl
// editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/',
// 高级用法:函数 editUrl
editUrl: ({locale, blogDirPath, blogPath, permalink}) =>
`https://github.com/facebook/docusaurus/edit/main/website/${blogDirPath}/${blogPath}`,
editLocalizedFiles: false,
blogTitle: 'Blog title',
blogDescription: 'Blog',
blogSidebarCount: 5,
blogSidebarTitle: 'All our posts',
routeBasePath: 'blog',
include: ['**/*.{md,mdx}'],
exclude: [
'**/_*.{js,jsx,ts,tsx,md,mdx}',
'**/_*/**',
'**/*.test.{js,jsx,ts,tsx}',
'**/__tests__/**',
],
postsPerPage: 10,
blogListComponent: '@theme/BlogListPage',
blogPostComponent: '@theme/BlogPostPage',
blogTagsListComponent: '@theme/BlogTagsListPage',
blogTagsPostsComponent: '@theme/BlogTagsPostsPage',
remarkPlugins: [require('./my-remark-plugin')],
rehypePlugins: [],
beforeDefaultRemarkPlugins: [],
beforeDefaultRehypePlugins: [],
truncateMarker: /<!--\s*(truncate)\s*-->/,
showReadingTime: true,
feedOptions: {
type: '',
title: '',
description: '',
copyright: '',
language: undefined,
createFeedItems: async (params) => {
const {blogPosts, defaultCreateFeedItems, ...rest} = params;
return defaultCreateFeedItems({
// 只保留最近 10 篇博客文章在 Feed 中
blogPosts: blogPosts.filter((item, index) => index < 10),
...rest,
});
},
},
};

Markdown front matter

Markdown 文档可以使用如下 Markdown front matter 元数据字段,需用 --- 包裹。

可用字段:

名称类型默认值说明
authorsAuthorsundefined博客文章作者列表(或唯一作者)。详见 authors 指南。即使是单作者博客,也推荐使用 authors 字段。
authorstringundefined⚠️ 推荐使用 authors。博客作者名称。
author_urlstringundefined⚠️ 推荐使用 authors。作者名称的链接地址,可以是 GitHub、X、Facebook 等个人主页。
author_image_urlstringundefined⚠️ 推荐使用 authors。作者头像图片的链接。
author_titlestringundefined⚠️ 推荐使用 authors。作者描述。
titlestringMarkdown 标题博客文章标题。
title_metastringfrontMatter.title博客 SEO 元数据标题,用于 <head><title>og:title。当展示标题和 SEO 标题需区分时可用。
datestring文件名或文件创建时间博客文章创建日期。未指定时可从文件名或文件夹名中提取,否则为 Markdown 文件创建时间。
tagsTag[]undefined文章标签字符串或对象数组。字符串可引用标签文件(通常为 tags.yml)中的 key。
draftbooleanfalse草稿博客文章仅在开发环境可见。
unlistedbooleanfalse未列出的博客文章在开发和生产环境均可访问,但在生产环境下会被"隐藏",不被索引、不会出现在 sitemap,只能通过直链访问。
hide_table_of_contentsbooleanfalse是否隐藏右侧目录。
toc_min_heading_levelnumber2目录中显示的最小标题级别。必须在 2 到 6 之间,且小于等于最大值。
toc_max_heading_levelnumber3目录中显示的最大标题级别。必须在 2 到 6 之间。
keywordsstring[]undefined关键词 meta 标签,将作为 <meta name="keywords" content="keyword1,keyword2,..."/> 出现在 <head>,供搜索引擎使用。
descriptionstringMarkdown 内容第一行文章描述,将作为 <meta name="description" content="..."/><meta property="og:description" content="..."/> 出现在 <head>,供搜索引擎使用。
imagestringundefined封面或缩略图,将作为 <meta property="og:image" content="..."/> 出现在 <head>,用于增强社交媒体和消息平台的链接预览效果。
slugstring文件路径自定义博客文章 URL(/<routeBasePath>/<slug>)。支持多种模式:slug: my-blog-postslug: /my/path/to/blog/post、slug: /
last_updateFrontMatterLastUpdateundefined可覆盖最后更新作者/日期。日期可为任意可解析的日期字符串
type FrontMatterLastUpdate = {date?: string; author?: string};

type Tag = string | {label: string; permalink: string};

// 作者 key 可引用全局插件 authors.yml 文件中的作者
// 社交平台名 -> 社交平台链接
// 示例: {MyPlatform: 'https://myplatform.com/myusername'}
// 预定义平台
// ("x", "github", "twitter", "linkedin", "stackoverflow", "instagram", "bluesky", "mastodon", "threads", "twitch", "youtube") 可直接填写用户名
// 示例: {github: 'slorber'}
type AuthorSocials = Record<string, string>;

type Author = {
key?: AuthorKey;
name: string;
title?: string;
url?: string;
image_url?: string;
socials?: AuthorSocials;
};

// front matter 的 authors 字段支持多种形态
// 见下方示例

示例:

---
title: Welcome Docusaurus
authors:
- slorber
- yangshun
- name: Joel Marcey
title: Co-creator of Docusaurus 1
url: https://github.com/JoelMarcey
image_url: https://github.com/JoelMarcey.png
socials:
x: joelmarcey
github: JoelMarcey
tags: [docusaurus]
description: 这是我在道格龙(Docusaurus)上的第一篇文章。
image: https://i.imgur.com/mErPwqL.png
hide_table_of_contents: false
---

一篇 Markdown 博客文章

标签文件

使用 tags 插件选项 配置 YAML 标签文件的路径。

按照惯例,插件会在你的内容文件夹根目录查找 tags.yml 文件。

该文件可以包含一组预定义标签。你可以在 Markdown 文件中通过 tags front matter 引用这些标签的 key。

保持标签一致性

通过标签文件,你可以确保在插件内容中标签的使用保持一致。使用 onInlineTags: 'throw' 插件选项可以强制执行这一规范,防止随意声明内联标签。

类型

提供的标签文件(YAML 格式)应遵循如下结构:

type Tag = {
label?: string; // 标签显示名称
permalink?: string; // 标签 URL 路径片段
description?: string; // 标签页中显示的标签描述
};

type TagsFileInput = Record<string, Partial<Tag> | null>;

示例

tags.yml
releases:
label: '产品发布'
permalink: '/product-releases'
description: '与产品发布相关的内容。'

# 只定义部分属性的标签也是有效的
announcements:
label: '公告'

# 空标签定义同样有效
# 其他属性会根据 key 自动推断
emptyTag:
content.md
---
tags: [releases, announcements, emptyTag]
---

# 标题

内容

作者文件

使用 authors 插件选项 配置 YAML 格式的作者文件路径。

约定上,插件会在你的博客内容文件夹根目录查找 authors.yml 文件。

该文件可包含全局博客作者的预定义列表。你可以在 Markdown 文件中通过 authors front matter 字段引用这些作者。

类型定义

YAML 作者文件内容应符合如下结构:

type AuthorsMapInput = {
[authorKey: string]: AuthorInput;
};

type AuthorInput = {
name?: string;
title?: string;
description?: string;
imageURL?: string;
url?: string;
email?: string;
page?: boolean | {permalink: string};
socials?: Record<string, string>;
[customAuthorAttribute: string]: unknown;
};

示例

tags.yml
slorber:
name: Sébastien Lorber
title: Docusaurus 维护者
url: https://sebastienlorber.com
image_url: https://github.com/slorber.png
page: true
socials:
x: sebastienlorber
github: slorber

jmarcey:
name: Joel Marcey
title: Docusaurus 1 联合创始人
url: https://github.com/JoelMarcey
image_url: https://github.com/JoelMarcey.png
email: [email protected]
page:
permalink: '/joel-marcey'
socials:
x: joelmarcey
github: JoelMarcey
blog/my-blog-post.md
---
authors: [slorber, jmarcey]
---

# 我的博客文章

内容

i18n

请先阅读i18n 介绍

翻译文件位置

  • 基础路径website/i18n/[locale]/docusaurus-plugin-content-blog
  • 多实例路径website/i18n/[locale]/docusaurus-plugin-content-blog-[pluginId]
  • JSON 文件:通过 docusaurus write-translations 提取
  • Markdown 文件website/i18n/[locale]/docusaurus-plugin-content-blog

文件系统结构示例

website/i18n/[locale]/docusaurus-plugin-content-blog

│ # website/blog 的翻译
├── authors.yml
├── first-blog-post.md
├── second-blog-post.md

│ # 渲染时用到的插件选项翻译
└── options.json