Modules are the building blocks of Nuxt. Kit provides a set of utilities to help you create and use modules. You can use these utilities to create your own modules or to reuse existing modules.
### `defineNuxtModule`
Define a Nuxt module, automatically merging defaults with user provided options, installing any hooks that are provided, and calling an optional setup function for full control.
#### Type
```ts
function defineNuxtModule<OptionsTextendsModuleOptions> (definition: ModuleDefinition<OptionsT> | NuxtModule<OptionsT>): NuxtModule<OptionsT>
Install specified Nuxt module programmatically. This is helpful when your module depends on other modules. You can pass the module options as an object to `inlineOptions` and they will be passed to the module's `setup` function.
Programmatic usage can be helpfull when you want to use Nuxt programmatically, for example, when building a [CLI tool](https://github.com/nuxt/cli) or [test utils](https://github.com/nuxt/nuxt/tree/main/packages/test-utils).
Loading conditions for Nuxt. `loadNuxt` uses [`c12`](https://github.com/unjs/c12) under the hood, so it accepts the same options as `c12.loadConfig` with some additional options:
If set to `true`, Nuxt will be loaded in development mode.
-`ready` (optional)
**Type**: `boolean`
**Default**: `true`
If set to `true`, Nuxt will be ready to use after the `loadNuxt` call. If set to `false`, you will need to call `nuxt.ready()` to make sure Nuxt is ready to use.
Build Nuxt programmatically. It will invoke the builder (currently [@nuxt/vite-builder](https://github.com/nuxt/nuxt/tree/main/packages/vite) or [@nuxt/webpack-builder](https://github.com/nuxt/nuxt/tree/main/packages/webpack)) to bundle the application.
Kit utilities can be used in Nuxt 3, Nuxt 2 with Bridge and Nuxt 2 without Bridge. To make sure your module is compatible with all versions, you can use the `checkNuxtCompatibility`, `assertNuxtCompatibility` and `hasNuxtCompatibility` functions. They will check if the current Nuxt version meets the constraints you provide. Also you can use `isNuxt2`, `isNuxt3` and `getNuxtVersion` functions for more granular checks.
Nuxt version in semver format. Versions may be defined in Node.js way, for exmaple: `>=2.15.0 <3.0.0`.
-`bridge` (optional)
**Type**: `boolean`
If set to `true`, it will check if the current Nuxt version supports `bridge`.
##### `nuxt`
**Type**: `Nuxt`
**Default**: `useNuxt()`
Nuxt instance. If not provided, it will be retrieved from the context via `useNuxt()` call.
### `hasNuxtCompatibility`
Checks if constraints are met for the current Nuxt version. Return `true` if all constraints are met, otherwise returns `false`. Nuxt 2 version also checks for `bridge` support.
#### Type
```ts
async function hasNuxtCompatibility(
constraints: NuxtCompatibility,
nuxt?: Nuxt
): Promise<boolean>;
interface NuxtCompatibility {
nuxt?: string;
bridge?: boolean;
}
```
#### Parameters
##### `constraints`
**Type**: `NuxtCompatibility`
**Default**: `{}`
Constraints to check for. It accepts the following properties:
These functions are designed for registering your own utils, composables and Vue APIs. For pages, components and plugins, please refer to the specific sections: [Pages](#pages), [Components](#components), [Plugins](#plugins).
Nuxt auto-imports helper functions, composables and Vue APIs to use across your application without explicitly importing them. Based on the directory structure, every Nuxt application can also use auto-imports for its own composables and plugins. Composables or plugins can use these functions.
Add imports from a directory to the Nuxt application. It will automatically import all files from the directory and make them available in the Nuxt application without the need to import them manually.
In Nuxt, components from the components directory are automatically imported by default. However, if you need to import components from an alternative directory or wish to selectively import them as needed, `@nuxt/kit` provides the `addComponentsDir` and `addComponent` methods. These utils allow you to customize the component configuration to better suit your needs.
Register a directory to be scanned for components and imported only when used. Keep in mind, that this does not register components globally, until you specify `global: true` option.
#### Type
```ts
async function addComponentsDir (dir: ComponentsDir): void
A function that will be called for each component found in the directory. It accepts a component object and should return a component object or a promise that resolves to a component object.
-`global` (optional)
**Type**: `boolean`
**Default**: `false`
If enabled, registers components to be globally available.
-`island` (optional)
**Type**: `boolean`
If enabled, registers components as islands.
-`watch` (optional)
**Type**: `boolean`
Watch specified path for changes, including file additions and file deletions.
-`extensions` (optional)
**Type**: `string[]`
Extensions supported by Nuxt builder.
-`transpile` (optional)
**Type**: `'auto' | boolean`
Transpile specified path using build.transpile. If set to `'auto'`, it will set `transpile: true` if `node_modules/` is in path.
Chunk name for the component. If not provided, it will be generated from the component name.
-`prefetch` (optional)
**Type**: `boolean`
These properties (prefetch/preload) are used in production to configure how components with Lazy prefix are handled by webpack via its magic comments.
Learn more on [webpack documentation](https://webpack.js.org/api/module-methods/#magic-comments)
-`preload` (optional)
**Type**: `boolean`
These properties (prefetch/preload) are used in production to configure how components with Lazy prefix are handled by webpack via its magic comments.
Learn more on [webpack documentation](https://webpack.js.org/api/module-methods/#magic-comments)
-`global` (optional)
**Type**: `boolean`
**Default**: `false`
If enabled, registers component to be globally available.
-`island` (optional)
**Type**: `boolean`
If enabled, registers component as island. You can read more about islands in [<NuxtIsland/>](/docs/api/components/nuxt-island#nuxtisland) component description.
-`mode` (optional)
**Type**: `'client' | 'server' | 'all'`
**Default**: `'all'`
This options indicates if component should render on client, server or both. By default, it will render on both client and server.
-`priority` (optional)
**Type**: `number`
**Default**: `1`
Priority of the component, if multiple components have the same name, the one with the highest priority will be used.
Nuxt modules allow you to enhance Nuxt's capabilities. They offer a structured way to keep your code organized and modular. If you're looking to break down your module into smaller components, Nuxt offers the `useNuxt` and `tryUseNuxt` functions. These functions enable you to conveniently access the Nuxt instance from the context without having to pass it as argument.
When you're working with the `setup` function in Nuxt modules, Nuxt is already provided as the second argument. This means you can directly utilize it without needing to call `useNuxt()`. You can look at [Nuxt Site Config](https://github.com/harlan-zw/nuxt-site-config) as an example of usage.
In Nuxt 3, routes are automatically generated based on the structure of the files in the `pages` directory. However, there may be scenarios where you'd want to customize these routes. For instance, you might need to add a route for a dynamic page not generated by Nuxt, remove an existing route, or modify the configuration of a route. For such customizations, Nuxt 3 offers the `extendPages` feature, which allows you to extend and alter the pages configuration.
A function that will be called with the pages configuration. You can alter this array by adding, deleting, or modifying its elements. Note: You should modify the provided pages array directly, as changes made to a copied array will not be reflected in the configuration.
Nuxt is powered by the [Nitro](https://nitro.unjs.io) server engine. With Nitro, you can incorporate high-level logic directly into your configuration, which is usefull for actions like redirects, proxying, caching, and appending headers to routes. This configuration works by associating route patterns with specific route settings.
::alert{type=info icon=👉}
You can read more about Nitro route rules in the [Nitro documentation](https://nitro.unjs.io/guide/routing#route-rules).
In Nuxt 2 `error` layout can also be registered using this utility. In Nuxt 3 `error` layout [replaced](/docs/getting-started/error-handling#rendering-an-error-page) with `error.vue` page in project root.
A template object or a string with the path to the template. If a string is provided, it will be converted to a template object with `src` set to the string value. If a template object is provided, it must have the following properties:
A function that will be called with the `options` object. It should return a string or a promise that resolves to a string. If `src` is provided, this function will be ignored.
-`write` (optional)
**Type**: `boolean`
If set to `true`, the template will be written to the destination file. Otherwise, the template will be used only in virtual filesystem.
function addPlugin (plugin: NuxtPlugin | string, options: AddPluginOptions): NuxtPlugin
interface NuxtPlugin {
src: string
mode?: 'all' | 'server' | 'client'
order?: number
}
interface AddPluginOptions { append?: boolean }
```
#### Parameters
##### `plugin`
**Type**: `NuxtPlugin | string`
**Required**: `true`
A plugin object or a string with the path to the plugin. If a string is provided, it will be converted to a plugin object with `src` set to the string value. If a plugin object is provided, it must have the following properties:
-`src` (required)
**Type**: `string`
Path to the plugin.
-`mode` (optional)
**Type**: `'all' | 'server' | 'client'`
**Default**: `'all'`
If set to `'all'`, the plugin will be included in both client and server bundles. If set to `'server'`, the plugin will only be included in the server bundle. If set to `'client'`, the plugin will only be included in the client bundle. You can also use `.client` and `.server` modifiers when specifying `src` option to use plugin only in client or server side.
-`order` (optional)
**Type**: `number`
**Default**: `0`
Order of the plugin. This allows more granular control over plugin order and should only be used by advanced users. Lower numbers run first, and user plugins default to `0`. It's recommended to set `order` to a number between `-20` for `pre`-plugins (plugins that run before Nuxt plugins) and `20` for `post`-plugins (plugins that run after Nuxt plugins).
::alert{type=warning}
Don't use `order` unless you know what you're doing. For most plugins, the default `order` of `0` is sufficient. To append a plugin to the end of the plugins array, use the `append` option instead.
::
##### `options`
**Type**: `AddPluginOptions`
**Default**: `{}`
Options to pass to the plugin. If `append` is set to `true`, the plugin will be appended to the plugins array instead of prepended.
#### Examples
::code-group
```ts [module.ts]
import { createResolver, defineNuxtModule, addPlugin } from '@nuxt/kit'
export default defineNuxtModule({
setup() {
const resolver = createResolver(import.meta.url)
addPlugin({
src: resolver.resolve('runtime/plugin.js'),
mode: 'client'
})
}
})
```
```ts [runtime/plugin.js]
// https://github.com/nuxt/nuxters
export default defineNuxtPlugin((nuxtApp) => {
const colorMode = useColorMode()
nuxtApp.hook('app:mounted', () => {
if (colorMode.preference !== 'dark') {
colorMode.preference = 'dark'
}
})
})
```
::
### `addPluginTemplate`
Adds a template and registers as a nuxt plugin. This is useful for plugins that need to generate code at build time.
#### Type
```ts
function addPluginTemplate (pluginOptions: NuxtPluginTemplate, options: AddPluginOptions): NuxtPlugin
A plugin template object with the following properties:
-`src` (optional)
**Type**: `string`
Path to the template. If `src` is not provided, `getContents` must be provided instead.
-`filename` (optional)
**Type**: `string`
Filename of the template. If `filename` is not provided, it will be generated from the `src` path. In this case, the `src` option is required.
-`dst` (optional)
**Type**: `string`
Path to the destination file. If `dst` is not provided, it will be generated from the `filename` path and nuxt `buildDir` option.
-`mode` (optional)
**Type**: `'all' | 'server' | 'client'`
**Default**: `'all'`
If set to `'all'`, the plugin will be included in both client and server bundles. If set to `'server'`, the plugin will only be included in the server bundle. If set to `'client'`, the plugin will only be included in the client bundle. You can also use `.client` and `.server` modifiers when specifying `src` option to use plugin only in client or server side.
A function that will be called with the `options` object. It should return a string or a promise that resolves to a string. If `src` is provided, this function will be ignored.
If set to `true`, the template will be written to the destination file. Otherwise, the template will be used only in virtual filesystem.
-`order` (optional)
**Type**: `number`
**Default**: `0`
Order of the plugin. This allows more granular control over plugin order and should only be used by advanced users. Lower numbers run first, and user plugins default to `0`. It's recommended to set `order` to a number between `-20` for `pre`-plugins (plugins that run before Nuxt plugins) and `20` for `post`-plugins (plugins that run after Nuxt plugins).
::alert{type=warning}
Don't use `order` unless you know what you're doing. For most plugins, the default `order` of `0` is sufficient. To append a plugin to the end of the plugins array, use the `append` option instead.
::
##### `options`
**Type**: `AddPluginOptions`
**Default**: `{}`
Options to pass to the plugin. If `append` is set to `true`, the plugin will be appended to the plugins array instead of prepended.
#### Examples
::code-group
```ts [module.ts]
// https://github.com/vuejs/vuefire
import { createResolver, defineNuxtModule, addPluginTemplate } from '@nuxt/kit'
export default defineNuxtModule({
setup() {
const resolver = createResolver(import.meta.url)
addPluginTemplate({
src: resolve(templatesDir, 'plugin.ejs'),
options: {
...options,
ssr: nuxt.options.ssr,
},
})
}
})
```
```ts [runtime/plugin.ejs]
import { VueFire, useSSRInitialState } from 'vuefire'
A template object or a string with the path to the template. If a string is provided, it will be converted to a template object with `src` set to the string value. If a template object is provided, it must have the following properties:
-`src` (optional)
**Type**: `string`
Path to the template. If `src` is not provided, `getContents` must be provided instead.
-`filename` (optional)
**Type**: `string`
Filename of the template. If `filename` is not provided, it will be generated from the `src` path. In this case, the `src` option is required.
-`dst` (optional)
**Type**: `string`
Path to the destination file. If `dst` is not provided, it will be generated from the `filename` path and nuxt `buildDir` option.
A function that will be called with the `options` object. It should return a string or a promise that resolves to a string. If `src` is provided, this function will be ignored.
-`write` (optional)
**Type**: `boolean`
If set to `true`, the template will be written to the destination file. Otherwise, the template will be used only in virtual filesystem.
If you are building an integration that needs access to the runtime Vite or webpack config that Nuxt uses, it is possible to extract this using Kit utilities.
Here is a brief example of how you might access the Vite config from a project; you could implement a similar approach to get the webpack configuration.