开发主题

::: tip 在阅读该指南之前,你最好先了解一下 开发插件 指南。 :::

创建一个主题

VuePress 主题是一个特殊的插件,它应该符合 主题 API 。和插件一样,主题可以是一个 主题对象 或一个 主题函数 ,并且通常通过一个函数来接收配置项:

  1. const { path } = require('@vuepress/utils')
  2. const fooTheme = (options) => {
  3. return {
  4. name: 'vuepress-theme-foo',
  5. layouts: {
  6. Layout: path.resolve(__dirname, 'layouts/Layout.vue'),
  7. 404: path.resolve(__dirname, 'layouts/404.vue'),
  8. },
  9. // ...
  10. }
  11. }
  12. const barTheme = (options) => {
  13. return (app) => {
  14. return {
  15. name: 'vuepress-theme-bar',
  16. layouts: {
  17. Layout: path.resolve(__dirname, 'layouts/Layout.vue'),
  18. 404: path.resolve(__dirname, 'layouts/404.vue'),
  19. },
  20. // ...
  21. }
  22. }
  23. }

layouts 字段声明了你的主题提供的布局。一个主题必须提供至少两个布局:Layout404 。前者用于提供一般页面的默认布局,后者用于提供 404 页面的布局。

Layout 布局应该包含 Content 组件来展示 Markdown 内容:

  1. <template>
  2. <div>
  3. <Content />
  4. </div>
  5. </template>

404 布局会被用于 404.html 页面:

  1. <template>
  2. <div>404 Not Found</div>
  3. </template>

你可以提供多个布局,用户可以通过 layout Frontmatter 来修改布局。

发布到 NPM

同样的,对于主题也有 package.json 相关的约定:

  1. {
  2. "name": "vuepress-theme-foo",
  3. "keywords": [
  4. "vuepress-theme"
  5. ]
  6. }
  • name 按照约定命名: vuepress-theme-xxx@org/vuepress-theme-xxx ,它应该和 主题对象name 字段保持一致。
  • keywords 中包含 vuepress-theme ,这样用户可以在 NPM 上搜索到你的主题。