Nuxt/docs/content/3.docs/2.directory-structure/8.modules.md
2021-11-21 13:31:44 +01:00

2.3 KiB

icon title navigation head.title
IconDirectory modules false Local modules directory

Local modules directory

Nuxt has a powerful modules engine.

Creating Modules

Nuxt provides helper functions (accessed from @nuxt/kit) to assist in creating modules that can run on both Nuxt 2 and Nuxt 3.

import { defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  // The npm package name of your module
  name: '@nuxtjs/sample-module',
  // The key in `nuxt.config` that holds your module options
  configKey: 'sample',
  // Default configuration options for your module
  defaults: {},
  hooks: {},
  setup (options, nuxt) {},
})

Module options

Nuxt will automatically merge the configuration provided to your module (whether passed directly inline or in a configuration section in nuxt.config) with the defaults you provide.

export default {
  buildModules: [
    ['@nuxtjs/sample-module', { sampleOption: true }]
  ],
  sample: {
    anotherOption: 42
  }
}

Hooks

For simple modules, you may be able to implement all you need simply with several hooks in this section.

Setup

If the hooks configuration is not enough, you can provide a full setup function, with access to nuxt. You will no longer have access to this as in the previous Nuxt module specification, but there are dedicated helper functions from @nuxt/kit to replace the module container methods from previously.

import { defineNuxtModule, addPlugin } from '@nuxt/kit'

export default defineNuxtModule({
  // ...
  setup (options, nuxt) {
    addPlugin({
      src: path.resolve(__dirname, 'templates/foo.js')
    })
  },
})

Advanced usage

In some cases you may need access to the Nuxt instance in order to define your module, for example, using other Nuxt options:

import { defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule(nuxt => ({
  // ...
  defaults: {
    root: nuxt.options.rootDir
  },
}))

Module helpers

A number of helpers are also provided for use within this context (with more coming - feature requests welcome) that ensure compatible behavior across Nuxt versions.

  • addTemplate
  • addErrorLayout
  • addLayout
  • addPlugin
  • addServerMiddleware
  • extendBuild
  • extendRoutes

Each of these functions provides documentation via IDE hover/autocomplete.

Publishing to NPM