Nuxt/docs/content/3.docs/4.advanced/2.modules.md
2022-01-29 21:43:48 +00:00

215 lines
7.9 KiB
Markdown

# Nuxt Modules
Nuxt provides a zero-config experience with a preset of integrations and best practices to develop Web applications.
A powerful configuration and hooks system makes it possible to customize almost every aspect of Nuxt Framework and add endless possible integrations when it comes to customization. You can learn more about how nuxt works in [Nuxt internals](/docs/advanced/nuxt) section.
Nuxt exposes a powerful API called **Nuxt Modules**. Nuxt modules are simple async functions that sequentially run when starting nuxt in development mode using `nuxi dev` or building a project for production with `nuxi build`.
Using Nuxt Modules, we can encapsulate, properly test and share custom solutions as npm packages without adding unnecessary boilerplate to the Nuxt project itself.
Nuxt Modules can hook into lifecycle events of Nuxt builder, provide runtime app templates, update the configuration or do any other custom action based on needs.
## Quick Start
For the impatient ones, You can quickly start with [module-builder](https://github.com/nuxt/module-builder) and [module starter template](https://github.com/nuxt/starter/tree/module):
```bash
npx nuxi init -t module my-module
```
Starter template and module starter is a standard path of creating a Nuxt module.
**Next steps:**
- Open `my-module` in IDE of your choice (VSCode is recommended)
- Install dependencies using the package manager of your choice (Yarn is recommended)
- Ensure local files are generated using `npm run prepare`
- Start playground using `npm run dev`
- **Follow this document to learn more about Nuxt modules**
::alert{type=warning icon=🚧}
This is an under-the-progress guide. Please regularly check for updates.
::
## Module Anatomy
A Nuxt module is a simple function accepting inline user options and `nuxt` arguments.
It is totally up to you, as the module author, how to handle the rest of the logic.
Starting with Nuxt 3, modules can benefit all [Nuxt Kit](/docs/advanced/kit) utilities.
```ts [modules/example.ts]
// modules/module.mjs
export default async (inlineOptions, nuxt) => {
// You can do whatever you like here..
console.log(inlineOptions.token) // `123`
console.log(nuxt.options.dev) // `true` or `false`
nuxt.hook('ready', async nuxt => {
console.log('Nuxt is ready')
})
}
```
```ts [nuxt.config]
export default defineNuxtConfig({
modules: [
// Using package name (recommanded usage)
'@nuxtjs/example',
// Load a local module
'./modules/example',
// Add module with inline-options
['./modules/example', { token: '123' }]
// Inline module definition
async (inlineOptions, nuxt) => { }
]
})
```
## Defining Nuxt Modules
Creating Nuxt modules involves tedious and common tasks. [Nuxt Kit](/docs/advanced/kit), provides a convenient and standard API to define Nuxt modules using `defineNuxtModule`:
```js
export default defineNuxtModule({
meta: {
// Usually npm package name of your module
name: '@nuxtjs/example',
// The key in `nuxt.config` that holds your module options
configKey: 'sample',
// Compatibility constraints
compatibility: {
// Semver version of supported nuxt versions
nuxt: '^3.0.0'
}
},
// Default configuration options for your module
defaults: {},
hooks: {},
async setup(moduleOptions, nuxt) {
// -- Add your module logic here --
}
})
```
Result of `defineNuxtModule` is a wrapper function with `(inlineOptions, nuxt)` signature. It applies defaults and other necessary steps and calls the`setup` function when called.
**`defineNuxtModule` features:**
- Support `defaults` and `meta.configKey` for automatically merging module options
- Type hints and automated type inference
- Add shims for basic Nuxt 2 compatibility
- Ensure module get's installed only once using a unique key computed from `meta.name` or `meta.configKey`
- Automatically register Nuxt hooks
- Automatically check for compatibility issues based on module meta
- Expose `getOptions` and `getMeta` for internal usage of Nuxt
- Ensuring backward and upward compatibility as long as the module is using `defineNuxtmodule` from the latest version of `@nuxt/kit`
- Integration with module builder tooling
## Best practices
### Async Modules
Nuxt Modules can do asynchronous operations. For example, you may want to develop a module that needs fetching some API or calling an async function.
::alert{type="warning"}
Be careful that `nuxi dev` waits for your module setup before going to the next module and starting the development server. Do time-consuming logic using deferred Nuxt hooks.
::
### Always prefix exposed interfaces
Nuxt Modules should provide an explicit prefix for any exposed configuration, plugin, API, composable, or component to avoid conflict with other modules and internals.
Ideally you should prefix them with your module name (If your module is called `nuxt-foo`, expose `<FooButton>` and `useFooBar()` and **not** `<Foo>` and `useBar()`)
### Be Typescript Friendly
Nuxt 3, has first-class typescript integration for the best developer experience.
Exposing types and using typescript to develop modules can benefit users even when not using typescript directly.
### Avoid CommonJS syntax
Nuxt 3, relies on native ESM. Please read [/concepts/esm](/concepts/esm) for more information.
## Modules Ecosystem
Nuxt tends to have a healthy and rich ecosystem of Nuxt modules and integrations. Here are some best practices if you want to jump in and contribute!
### Document Module Usage
Consider documenting module usage in the readme file:
- Why use this module
- How to use this module
- What this module does?
Linking to the integration website and documentation is always a good idea.
### Use `nuxt-` prefix for npm packages
To make your modules discoverable, use `nuxt-` prefix for the npm package name. This is always the best starting point to draft and try an idea!
### Listing module to modules.nuxtjs.org
Do you have a working Module and want it listed in [modules.nuxtjs.org](https://modules.nuxtjs.org)? Open an issue in [nuxt/modules](https://github.com/nuxt/modules/issues/new) repository.
Nuxt team can help you to apply best practices before listing.
### Do not advertise with a specific Nuxt version
Nuxt 3, Nuxt Kit, and other new toolings are made to have both forward and backward compatibility in mind.
Please use "X for Nuxt" instead of "X for Nuxt 3" to avoid fragmentation in the ecosystem and prefer using `meta.compatibility` to set Nuxt version constraints.
### Joining nuxt-community
By moving your modules to [nuxt-community](https://github.com/nuxt-community), there is always someone else to help, and this way, we can join forces to make one perfect solution.
If you have an already published and working module and want to transfer it to nuxt-community, open an issue in [nuxt/modules](https://github.com/nuxt/modules/issues/new).
## Examples
### Provide Nuxt Plugins
Commonly, modules provide one or more run plugins to add runtime logic.
```ts
import { resolve } from 'path'
import { fileURLToPath } from 'url'
import { defineNuxtModule, addPlugin } from '@nuxt/kit'
export default defineNuxtModule<ModuleOptions>({
setup (options, nuxt) {
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
addPlugin(resolve(runtimeDir, 'plugin'))
}
})
```
### Add a CSS Library
If your module will provide a CSS library, make sure to check if the user already included the library to avoid duplicates and add an option to disable the CSS library in the module.
```ts
export default defineNuxtModule({
setup (options, nuxt) {
nuxt.options.css.push('font-awesome/css/font-awesome.css')
}
})
```
### Cleanup Module
If your module opens handles or starts a watcher, we should close it when the nuxt lifecycle is done. For this, we can use the `close` hook:
```ts
export default defineNuxtModule({
setup (options, nuxt) {
nuxt.hook('close', async nuxt => {
// Your custom code here
})
}
})
```