Writing a Theme

TIP

Before reading this guide, you’d better learn the guide of Writing a Plugin first.

Create a Theme

A VuePress theme is a special plugin, which should satisfy the Theme API. Like plugins, a theme can also be a Theme Object or a Theme Function.

  • Theme Object
  • Theme Function
  1. const fooTheme = {
  2. name: 'vuepress-theme-foo',
  3. layouts: {
  4. Layout: path.resolve(__dirname, 'layouts/Layout.vue'),
  5. 404: path.resolve(__dirname, 'layouts/404.vue'),
  6. },
  7. // ...
  8. }
  1. const fooTheme = (options, app) => {
  2. return {
  3. name: 'vuepress-theme-foo',
  4. layouts: {
  5. Layout: path.resolve(__dirname, 'layouts/Layout.vue'),
  6. 404: path.resolve(__dirname, 'layouts/404.vue'),
  7. },
  8. // ...
  9. }
  10. }

The layouts field declares the layouts provided by your theme.

A theme must provide at least two layouts: Layout and 404.

The Layout layout should contain the Content component to display the markdown content:

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

The 404 layout will be used for the 404.html page:

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

You can provide more layouts, and users can change layout via layout frontmatter.

Publish to NPM

The typical structure of a theme package is as follow:

  1. vuepress-theme-foo
  2. ├─ lib
  3. ├─ layouts
  4. ├─ Layout.vue
  5. └─ 404.vue
  6. └─ index.js
  7. └─ package.json

Theme Entry

The lib/index.js file is the theme entry, which should export the theme directly:

  • CJS
  • ESM
  1. module.export = fooTheme
  1. export default fooTheme

TIP

Notice that the theme entry will be loaded in Node, so it should be in CommonJS format.

If you are using ESM format, you’ll need to use babelWriting a Theme - 图1open in new window or typescriptWriting a Theme - 图2open in new window to transpile it into CommonJS.

package.json

The package.jsonWriting a Theme - 图3open in new window file is required to publish a package to NPM:

  1. {
  2. "name": "vuepress-theme-foo",
  3. "version": "1.0.0",
  4. "keywords": [
  5. "vuepress-theme",
  6. ],
  7. "main": "lib/index.js",
  8. "files": [
  9. "lib"
  10. ]
  11. }
  • Set name to follow the naming convention: vuepress-theme-xxx or @org/vuepress-theme-xxx.
  • Set keywords to include vuepress-theme, so that users can search your theme on NPM.
  • Set main to the theme entry file.
  • Set files to only publish those files inside lib directory.