Skip to content

register-components

@vuepress/plugin-register-components

Register Vue components from component files or directory automatically.

Usage

npm i -D @vuepress/plugin-register-components@next
.vuepress/config.ts
import { registerComponentsPlugin } from '@vuepress/plugin-register-components'

export default {
  plugins: [
    registerComponentsPlugin({
      // options
    }),
  ],
}

Guide

Register from Directory

Set componentsDir to the absolute path of the components directory. Files in this directory which are matched with componentsPatterns will be registered as Vue components automatically, and the component name is generated by getComponentName from the file path relative to componentsDir.

Component names must be unique. The plugin throws an error if multiple files get the same component name, so adjust getComponentName to generate distinct names in that case.

With the following components directory:

components
├─ FooBar.vue
└─ Baz.vue

Components will be registered like this:

import { defineAsyncComponent } from 'vue'

app.component(
  'FooBar',
  defineAsyncComponent(() => import('/path/to/components/FooBar.vue')),
)

app.component(
  'Baz',
  defineAsyncComponent(() => import('/path/to/components/Baz.vue')),
)

Options

componentsRecord<string, string>
Default {}

An object that defines the name of components and their corresponding file path.

The key will be used as the component name, and the value is an absolute path of the component file.

If the component name from this option conflicts with componentsDir option, this option will have a higher priority.

.vuepress/config.ts
import { path } from 'vuepress/utils'

const __dirname = import.meta.dirname

export default {
  plugins: [
    registerComponentsPlugin({
      components: {
        FooBar: path.resolve(__dirname, './components/FooBar.vue'),
      },
    }),
  ],
}
componentsDirstring | null
Default null

Absolute path to the components directory.

.vuepress/config.ts
import { path } from 'vuepress/utils'

const __dirname = import.meta.dirname

export default {
  plugins: [
    registerComponentsPlugin({
      componentsDir: path.resolve(__dirname, './components'),
    }),
  ],
}

See also: Register from Directory.

componentsPatternsstring[]
Default['**/*.vue']

Patterns to match component files using tinyglobby.

The patterns are relative to componentsDir.

getComponentName(filename: string) => string
Default(filename) => path.trimExt(filename.replaceAll(/\/|\\/gu, '-'))

A function to get the component name from the filename.

It will only take effect on the files in the componentsDir which are matched with the componentsPatterns.

Notice that the filename is a filepath relative to componentsDir.

MIT Licensed