📦 plugin-content-blog
Docusaurus 的默认博客插件,提供了博客功能。
订阅源功能通过提取构建输出实现,仅在生产环境中可用。
安装流程
- npm
- Yarn
- pnpm
npm install --save @docusaurus/plugin-content-blog
yarn add @docusaurus/plugin-content-blog
pnpm add @docusaurus/plugin-content-blog
如果你已经安装了 @docusaurus/preset-classic
,就不需要安装这个包了。
You can configure this plugin through the preset options.
配置
接受的字段:
参数 | 类型 | 默认值 | 描述 |
---|---|---|---|
path | string | 'blog' | 博客内容目录的文件系统路径,相对于站点目录。 |
editUrl | string | EditUrlFn | undefined | 编辑文档的基础 URL。 最终的 URL 会按照 editUrl + relativePostPath 计算。 使用函数可以允许你更精细地控制每一个文件。 完全忽略这个变量就会禁用编辑链接。 |
editLocalizedFiles | boolean | false | 编辑 URL 会指向本地化的文件,而不是原始的未翻译文件。 如果 editUrl 是一个函数,会完全忽略此选项。 |
blogTitle | string | 'Blog' | 用于增进 SEO 的博客页面标题。 |
blogDescription | string | 'Blog' | 用于增进 SEO 的博客页面元描述。 |
blogSidebarCount | number | 'ALL' | 5 | 在博客侧边栏中展示的博文项目数量。 'ALL' 会显示所有博文;0 会禁用侧边栏。 |
blogSidebarTitle | string | 'Recent posts' | 博客侧边栏的标题。 |
routeBasePath | string | 'blog' | 站点博客部分的 URL 前缀。 不要包含末尾斜杠。 / 会把博客放在根路径。 |
tagsBasePath | string | 'tags' | 博客标签部分的 URL 前缀。 会被添加到 routeBasePath 后面。 |
pageBasePath | string | 'page' | URL route for the pages section of your blog. 会被添加到 routeBasePath 后面。 |
archiveBasePath | string | null | 'archive' | 博客归档部分的 URL 前缀。 会被添加到 routeBasePath 后面。 不要包含末尾斜杠。 null 会禁止生成博客归档。 |
authorsBasePath | string | 'authors' | URL route for the authors pages of your blog. Will be appended to path . |
include | string[] | ['**/*.{md,mdx}'] | 相对于内容路径的 glob 模式列表,匹配到的 Markdown 文件会被构建。 |
exclude | string[] | 见示例配置 | Glob 模式列表,匹配到的 Markdown 文件会被排除。 在 include 选项的基础上进一步细调。 |
postsPerPage | number | 'ALL' | 10 | 每个博文列表页面显示的博文数量。 'ALL' 会让所有博文都展示在一个列表页上。 |
blogListComponent | string | '@theme/BlogListPage' | 博客列表页的根组件。 |
blogPostComponent | string | '@theme/BlogPostPage' | 每个博文页面的根组件。 |
blogTagsListComponent | string | '@theme/BlogTagsListPage' | 标签列表页的根组件。 |
blogTagsPostsComponent | string | '@theme/BlogTagsPostsPage' | 「包含某标签的所有博文」页面的根组件。 |
blogArchiveComponent | string | '@theme/BlogArchivePage' | 博客归档页的根组件。 |
blogAuthorsPostsComponent | string | '@theme/Blog/Pages/BlogAuthorsPostsPage' | Root component of the blog author page. |
blogAuthorsListComponent | string | '@theme/Blog/Pages/BlogAuthorsListPage' | Root component of the blog authors page index. |
remarkPlugins | any[] | [] | 传递给 MDX 的 Remark 插件。 |
rehypePlugins | any[] | [] | 传递给 MDX 的 Rehype 插件。 |
rehypePlugins | any[] | [] | Recma plugins passed to MDX. |
beforeDefaultRemarkPlugins | any[] | [] | 在 Docusaurus 默认 Remark 插件之前传递给 MDX 的自定义 Remark 插件。 |
beforeDefaultRehypePlugins | any[] | [] | 在 Docusaurus 默认 Rehype 插件之前传递给 MDX 的自定义 Rehype 插件。 |
truncateMarker | RegExp | /<!--\s*truncate\s*-->/ \ | \{\/\*\s*truncate\s*\*\/\}/ |
showReadingTime | boolean | true | 在博文上显示估计阅读时间。 |
readingTime | ReadingTimeFn | 默认阅读时间 | 用于自定义显示的阅读时间数字的回调。 |
authorsMapPath | string | 'authors.yml' | 作者记录表的文件路径,相对于博客内容目录。 |
feedOptions | 见下文 | {type: ['rss', 'atom']} | 博客订阅源。 |
feedOptions.type | FeedType | FeedType[] | 'all' | null | 必填 | 要生成的订阅源类型。 null 会禁用订阅源生成。 |
feedOptions.createFeedItems | CreateFeedItemsFn | undefined | undefined | An optional function which can be used to transform and / or filter the items in the feed. |
feedOptions.limit | number | null | false | 20 | Limits the feed to the specified number of posts, false or null for all entries. Defaults to 20 . |
feedOptions.title | string | siteConfig.title | 订阅源的标题。 |
feedOptions.description | string | `${siteConfig.title} Blog` | 订阅源的描述。 |
feedOptions.copyright | string | undefined | 版权信息。 |
feedOptions.xslt | boolean | FeedXSLTOptions | undefined | Permits to style the blog XML feeds with XSLT so that browsers render them nicely. |
feedOptions.language | string (所有可选值请见文档) | undefined | 订阅源的语言元数据。 |
sortPosts | 'descending' | 'ascending' | 'descending' | 决定博文排序的方向。 |
processBlogPosts | ProcessBlogPostsFn | undefined | An optional function which can be used to transform blog posts (filter, modify, delete, etc...). |
showLastUpdateAuthor | boolean | false | Whether to display the author who last updated the blog post. |
showLastUpdateTime | boolean | false | Whether to display the last date the blog post was updated. This requires access to git history during the build, so will not work correctly with shallow clones (a common default for CI systems). With GitHub actions/checkout , usefetch-depth: 0 . |
tags | string | false | null | undefined | tags.yml | Path to the YAML tags file listing pre-defined tags. Relative to the blog content directory. |
onInlineTags | 'ignore' | 'log' | 'warn' | 'throw' | warn | The plugin behavior when blog posts contain inline tags (not appearing in the list of pre-defined tags, usually tags.yml ). |
onUntruncatedBlogPosts | 'ignore' | 'log' | 'warn' | 'throw' | warn | The plugin behavior when blog posts do not contain a truncate marker. |
类型
EditUrlFn
type EditUrlFunction = (params: {
blogDirPath: string;
blogPath: string;
permalink: string;
locale: string;
}) => string | undefined;
ReadingTimeFn
type ReadingTimeOptions = {
wordsPerMinute: number;
wordBound: (char: string) => boolean;
};
type ReadingTimeCalculator = (params: {
content: string;
frontMatter?: BlogPostFrontMatter & Record<string, unknown>;
options?: ReadingTimeOptions;
}) => number;
type ReadingTimeFn = (params: {
content: string;
frontMatter: BlogPostFrontMatter & Record<string, unknown>;
defaultReadingTime: ReadingTimeCalculator;
}) => number | undefined;
FeedType
type FeedType = 'rss' | 'atom' | 'json';
FeedXSLTOptions
Permits to style the blog XML feeds so that browsers render them nicely with XSLT.
- Use
true
to let the blog use its built-in.xsl
and.css
files to style the blog feed - Use a falsy value (
undefined | null | false
) to disable the feature - Use a
string
to provide a file path to a custom.xsl
file relative to the blog content folder. By convention, you must provide a.css
file with the exact same name.
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[]>;
示例配置
你可以通过预设选项或插件选项来配置这个插件。
大多数 Docusaurus 用户通过预设选项配置此插件。
- 预设选项
- 插件选项
如果你使用预设,你可以通过预设选项配置这个插件:
module.exports = {
presets: [
[
'@docusaurus/preset-classic',
{
blog: {
path: 'blog',
// Simple use-case: string editUrl
// editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/',
// Advanced use-case: functional 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({
// keep only the 10 most recent blog posts in the feed
blogPosts: blogPosts.filter((item, index) => index < 10),
...rest,
});
},
},
},
},
],
],
};
如果你用的是独立插件,直接向插件提供选项:
module.exports = {
plugins: [
[
'@docusaurus/plugin-content-blog',
{
path: 'blog',
// Simple use-case: string editUrl
// editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/',
// Advanced use-case: functional 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({
// keep only the 10 most recent blog posts in the feed
blogPosts: blogPosts.filter((item, index) => index < 10),
...rest,
});
},
},
},
],
],
};
Markdown 前言
Markdown documents can use the following Markdown front matter metadata fields, enclosed by a line ---
on either side.
接受的字段:
参数 | 类型 | 默认值 | 描述 |
---|---|---|---|
authors | Authors | undefined | 博文作者列表(或者唯一作者)。 更多阐释可以参见 authors 指南。 即使文章只有一个作者,也推荐用 authors 而不是 author_* 字段。 |
author | string | undefined | ⚠️ 推荐使用 authors 。 博文作者的名字。 |
author_url | string | undefined | ⚠️ 推荐使用 authors 。 作者名字链接指向的 URL。 This could be a GitHub, X, Facebook profile URL, etc. |
author_image_url | string | undefined | ⚠️ 推荐使用 authors 。 作者头像图片的 URL。 |
author_title | string | undefined | ⚠️ 推荐使用 authors 。 作者的描述。 |
title | string | Markdown 标题 | 博文的标题。 |
date | string | 文件名或文件创建时间 | 博文的创建时间。 如果未给定,会从文件或文件夹名称中提取,例如:2021-04-15-blog-post.mdx 、2021-04-15-blog-post/index.mdx 、2021/04/15/blog-post.mdx 。 如果也没有,会使用 Markdown 文件的创建时间。 |
tags | Tag[] | undefined | 一个列表,由字符串或者包含 label 和 permalink 字符串字段的对象构成,用于提供博文标签。 Strings can be a reference to keys of a tags file (usually tags.yml ) |
draft | boolean | false | Draft blog posts will only be available during development. |
unlisted | boolean | false | Unlisted blog posts will be available in both development and production. They will be "hidden" in production, not indexed, excluded from sitemaps, and can only be accessed by users having a direct link. |
hide_table_of_contents | boolean | false | 是否隐藏右侧的文档目录。 |
toc_min_heading_level | number | 2 | 目录中显示的最小标题层级。 必须介于 2 到 6 之间,并且小于等于最大值。 |
toc_max_heading_level | number | 3 | 目录中显示的最大标题层级。 必须介于 2 和 6。 |
keywords | string[] | undefined | 关键词元标签,会变成 <head> 中的 <meta name="keywords" content="keyword1,keyword2,..."/> ,被搜索引擎使用。 |
description | string | Markdown 正文的第一行 | 文档的描述信息,会生成 <head> 中被搜索引擎读取的 <meta name="description" content="..."/> 和 <meta property="og:description" content="..."/> 。 |
image | string | undefined | Cover or thumbnail image that will be used as the <meta property="og:image" content="..."/> in the <head> , enhancing link previews on social media and messaging platforms. |
slug | string | 文件路径 | 自定义博文的 URL (/<routeBasePath>/<slug> )。 支持多种形式: slug: my-blog-post 、slug: /my/path/to/blog/post 、slug: / 。 |
last_update | FrontMatterLastUpdate | undefined | Allows overriding the last update author/date. 日期可以是任意可解析的日期字符串。 |
type FrontMatterLastUpdate = {date?: string; author?: string};
type Tag = string | {label: string; permalink: string};
// An author key references an author from the global plugin authors.yml file
type AuthorKey = string;
// Social platform name -> Social platform link
// Example: {MyPlatform: 'https://myplatform.com/myusername'}
// Pre-defined platforms ("x", "github", "twitter", "linkedin", "stackoverflow") accept handles:
// Example: {github: 'slorber'}
type AuthorSocials = Record<string, string>;
type Author = {
key?: AuthorKey;
name: string;
title?: string;
url?: string;
image_url?: string;
socials?: AuthorSocials;
};
// The front matter authors field allows various possible shapes
type Authors = AuthorKey | Author | (AuthorKey | Author)[];
示例:
---
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: This is my first post on Docusaurus.
image: https://i.imgur.com/mErPwqL.png
hide_table_of_contents: false
---
一篇 Markdown 博文
Tags File
Use the tags
plugin option to configure the path of a YAML tags file.
By convention, the plugin will look for a tags.yml
file at the root of your content folder(s).
This file can contain a list of predefined tags. You can reference these tags by their keys in Markdown files thanks to the tags
front matter.
Using a tags file, you can ensure that your tags usage is consistent across your plugin content set. Use the onInlineTags: 'throw'
plugin option to enforce this consistency and prevent usage of inline tags declared on the fly.
Types
The YAML content of the provided tags file should respect the following shape:
type Tag = {
label?: string; // Tag display label
permalink?: string; // Tag URL pathname segment
description?: string; // Tag description displayed in the tag page
};
type TagsFileInput = Record<string, Partial<Tag> | null>;
Example
releases:
label: 'Product releases'
permalink: '/product-releases'
description: 'Content related to product releases.'
# A partial tag definition is also valid
announcements:
label: 'Announcements'
# An empty tag definition is also valid
# Other attributes will be inferred from the key
emptyTag:
---
tags: [releases, announcements, emptyTag]
---
# Title
Content
Authors File
Use the authors
plugin option to configure the path of a YAML authors file.
By convention, the plugin will look for a authors.yml
file at the root of your blog content folder(s).
This file can contain a list of predefined global blog authors. You can reference these authors by their keys in Markdown files thanks to the authors
front matter.
类型
The YAML content of the provided authors file should respect the following shape:
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;
};
示例
slorber:
name: Sébastien Lorber
title: Docusaurus maintainer
url: https://sebastienlorber.com
image_url: https://github.com/slorber.png
page: true
socials:
x: sebastienlorber
github: slorber
jmarcey:
name: Joel Marcey
title: Co-creator of 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
---
authors: [slorber, jmarcey]
---
# My Blog Post
Content
i18n
Read the i18n introduction first.
翻译文件位置
- 基础路径:
website/i18n/[语言]/docusaurus-plugin-content-blog
- 多实例路径:
website/i18n/[语言]/docusaurus-plugin-content-blog-[插件 ID]
- JSON files: extracted with
docusaurus write-translations
- Markdown 文件:
website/i18n/[语言]/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