Nuxt/docs/content/3.docs/2.directory-structure/8.modules.md
2021-10-12 16:57:34 +02:00

97 lines
2.3 KiB
Markdown

---
icon: IconDirectory
title: 'modules'
navigation: false
head.title: Local modules directory
---
# Local modules directory
Nuxt has a powerful [modules engine](/concepts/modules).
# 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.
```js
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.
```js
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.
```js
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:
```js
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