Writing a Plugin

TIP

Before reading this guide, you’d better learn the VuePress architecture first.

Create a Plugin

A VuePress plugin is a plain JavaScript object that satisfies the Plugin API, which is called a Plugin Object.

If a plugin wants to receive user options, it could be a function that returns a Plugin Object, which is called a Plugin Function.

  • Plugin Object
  • Plugin Function
  1. const fooPlugin = {
  2. name: 'vuepress-plugin-foo',
  3. // ...
  4. }
  1. const fooPlugin = (options, app) => {
  2. return {
  3. name: 'vuepress-plugin-foo',
  4. // ...
  5. }
  6. }

Publish to NPM

The typical structure of a plugin package is as follow:

  1. vuepress-plugin-foo
  2. ├─ lib
  3. └─ index.js
  4. └─ package.json

Plugin Entry

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

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

TIP

Notice that the plugin 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 Plugin - 图1open in new window or typescriptWriting a Plugin - 图2open in new window to transpile it into CommonJS.

package.json

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

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