Модули
Модули являются строительными блоками Nuxt. Kit предоставляет набор утилит, которые помогают вам создавать и использовать модули. Вы можете использовать эти утилиты для создания своих собственных модулей или повторного использования существующих модулей. Например, вы можете использовать функцию defineNuxtModule для определения модуля и функцию installModule для программной установки модуля.
defineNuxtModule
Определяет модуль Nuxt, автоматически объединяя значения по умолчанию с предоставленными пользователем параметрами, устанавливая любые предоставленные хуки и вызывая необязательную функцию настройки для полного управления.
Usage
import { defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
meta: {
name: 'my-module',
configKey: 'myModule'
},
defaults: {
enabled: true
},
setup (options) {
if (options.enabled) {
console.log('My Nuxt module is enabled!')
}
}
})
Тип
// @errors: 2391
import type { ModuleDefinition, ModuleOptions, NuxtModule } from '@nuxt/schema'
// ---cut---
export function defineNuxtModule<TOptions extends ModuleOptions> (
definition?: ModuleDefinition<TOptions, Partial<TOptions>, false> | NuxtModule<TOptions, Partial<TOptions>, false>,
): NuxtModule<TOptions, TOptions, false>
export function defineNuxtModule<TOptions extends ModuleOptions> (): {
with: <TOptionsDefaults extends Partial<TOptions>> (
definition: ModuleDefinition<TOptions, TOptionsDefaults, true> | NuxtModule<TOptions, TOptionsDefaults, true>
) => NuxtModule<TOptions, TOptionsDefaults, true>
}
Параметры
definition: A module definition object or a module function. The module definition object should contain the following properties:
| Property | Type | Required | Description |
|---|---|---|---|
meta | ModuleMeta | false | Metadata of the module. It defines the module name, version, config key and compatibility. |
defaults | T | ((nuxt: Nuxt) => T) | false | Default options for the module. If a function is provided, it will be called with the Nuxt instance as the first argument. |
schema | T | false | Schema for the module options. If provided, options will be applied to the schema. |
hooks | Partial<NuxtHooks> | false | Hooks to be installed for the module. If provided, the module will install the hooks. |
setup | (this: void, resolvedOptions: T, nuxt: Nuxt) => Awaitable<void | false | ModuleSetupInstallResult> | false | Setup function for the module. If provided, the module will call the setup function. |
Примеры
Using configKey to Make Your Module Configurable
When defining a Nuxt module, you can set a configKey to specify how users should configure the module in their nuxt.config.
import { defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
meta: {
name: 'my-module',
configKey: 'myModule'
},
defaults: {
// Module options
enabled: true
},
setup (options) {
if (options.enabled) {
console.log('My Nuxt module is enabled!')
}
}
})
Users can provide options for this module under the corresponding key in nuxt.config.
export default defineNuxtConfig({
myModule: {
enabled: false
}
})
Defining Module Compatibility Requirements
If you're developing a Nuxt module and using APIs that are only supported in specific Nuxt versions, it's highly recommended to include compatibility.nuxt.
export default defineNuxtModule({
meta: {
name: '@nuxt/icon',
configKey: 'icon',
compatibility: {
// Required nuxt version in semver format.
nuxt: '>=3.0.0', // or use '^3.0.0'
},
},
async setup() {
const resolver = createResolver(import.meta.url)
// Implement
},
})
If the user tries to use your module with an incompatible Nuxt version, they will receive a warning in the console.
WARN Module @nuxt/icon is disabled due to incompatibility issues:
- [nuxt] Nuxt version ^3.1.0 is required but currently using 3.0.0
Type Safety for Resolved Options with .with()
When you need type safety for your resolved/merged module options, you can use the .with() method. This enables TypeScript to properly infer the relationship between your module's defaults and the final resolved options that your setup function receives.
import { defineNuxtModule } from '@nuxt/kit'
// Define your module options interface
interface ModuleOptions {
apiKey: string
baseURL: string
timeout?: number
retries?: number
}
export default defineNuxtModule<ModuleOptions>().with({
meta: {
name: '@nuxtjs/my-api',
configKey: 'myApi'
},
defaults: {
baseURL: 'https://api.example.com',
timeout: 5000,
retries: 3
},
setup(resolvedOptions, nuxt) {
// resolvedOptions is properly typed as:
// {
// apiKey: string // Required, no default provided
// baseURL: string // Required, has default value
// timeout: number // Optional, has default value
// retries: number // Optional, has default value
// }
console.log(resolvedOptions.baseURL) // ✅ TypeScript knows this is always defined
console.log(resolvedOptions.timeout) // ✅ TypeScript knows this is always defined
console.log(resolvedOptions.retries) // ✅ TypeScript knows this is always defined
}
})
Without using .with(), the resolvedOptions parameter would be typed as the raw ModuleOptions interface, where timeout and retries could be undefined even when defaults are provided. The .with() method enables TypeScript to understand that default values make those properties non-optional in the resolved options.
installModule
Устанавливает указанный модуль Nuxt программно. Это полезно, когда ваш модуль зависит от других модулей. Вы можете передать параметры модуля в виде объекта в inlineOptions, и они будут переданы в функцию setup модуля.
Usage
import { defineNuxtModule, installModule } from '@nuxt/kit'
export default defineNuxtModule({
async setup () {
// will install @nuxtjs/fontaine with Roboto font and Impact fallback
await installModule('@nuxtjs/fontaine', {
// module configuration
fonts: [
{
family: 'Roboto',
fallbacks: ['Impact'],
fallbackName: 'fallback-a',
}
]
})
}
})
Type
async function installModule (moduleToInstall: string | NuxtModule, inlineOptions?: any, nuxt?: Nuxt)
Параметры
| Property | Type | Required | Description |
|---|---|---|---|
moduleToInstall | string | NuxtModule | true | The module to install. Can be either a string with the module name or a module object itself. |
inlineOptions | any | false | An object with the module options to be passed to the module's setup function. |
nuxt | Nuxt | false | Nuxt instance. If not provided, it will be retrieved from the context via useNuxt() call. |
Примеры
import { defineNuxtModule, installModule } from '@nuxt/kit'
export default defineNuxtModule({
async setup (options, nuxt) {
// установит @nuxtjs/fontaine с шрифтом Roboto и запасным шрифтом Impact
await installModule('@nuxtjs/fontaine', {
// конфигурация модуля
fonts: [
{
family: 'Roboto',
fallbacks: ['Impact'],
fallbackName: 'fallback-a',
}
]
})
}
})