mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-27 08:02:01 +00:00
1364 lines
30 KiB
Markdown
1364 lines
30 KiB
Markdown
---
|
|
title: "Kit Utilities"
|
|
description: Nuxt Kit provides composable utilities to help interacting with Nuxt Hooks and Nuxt Builder.
|
|
---
|
|
|
|
# Kit Utilities
|
|
|
|
::ReadMore{link="/docs/guide/going-further/kit"}
|
|
::
|
|
|
|
## Modules
|
|
|
|
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/module)
|
|
|
|
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<OptionsT extends ModuleOptions> (definition: ModuleDefinition<OptionsT> | NuxtModule<OptionsT>): NuxtModule<OptionsT>
|
|
|
|
type ModuleOptions = Record<string, any>
|
|
|
|
interface ModuleDefinition<T extends ModuleOptions = ModuleOptions> {
|
|
meta?: ModuleMeta
|
|
defaults?: T | ((nuxt: Nuxt) => T)
|
|
schema?: T
|
|
hooks?: Partial<NuxtHooks>
|
|
setup?: (this: void, resolvedOptions: T, nuxt: Nuxt) => Awaitable<void | false | ModuleSetupReturn>
|
|
}
|
|
|
|
interface NuxtModule<T extends ModuleOptions = ModuleOptions> {
|
|
(this: void, inlineOptions: T, nuxt: Nuxt): Awaitable<void | false | ModuleSetupReturn>
|
|
getOptions?: (inlineOptions?: T, nuxt?: Nuxt) => Promise<T>
|
|
getMeta?: () => Promise<ModuleMeta>
|
|
}
|
|
|
|
interface ModuleSetupReturn {
|
|
timings?: {
|
|
setup?: number
|
|
[key: string]: number | undefined
|
|
}
|
|
}
|
|
|
|
interface ModuleMeta {
|
|
name?: string
|
|
version?: string
|
|
configKey?: string
|
|
compatibility?: NuxtCompatibility
|
|
[key: string]: unknown
|
|
}
|
|
```
|
|
|
|
#### Parameters
|
|
|
|
##### `definition`
|
|
|
|
**Type**: `ModuleDefinition<T> | NuxtModule<T>`
|
|
|
|
**Required**: `true`
|
|
|
|
A module definition object or a module function.
|
|
|
|
- `meta` (optional)
|
|
|
|
**Type**: `ModuleMeta`
|
|
|
|
Metadata of the module. It defines the module name, version, config key and compatibility.
|
|
|
|
- `defaults` (optional)
|
|
|
|
**Type**: `T | ((nuxt: Nuxt) => T)`
|
|
|
|
Default options for the module. If a function is provided, it will be called with the Nuxt instance as the first argument.
|
|
|
|
- `schema` (optional)
|
|
|
|
**Type**: `T`
|
|
|
|
Schema for the module options. If provided, options will be applied to the schema.
|
|
|
|
- `hooks` (optional)
|
|
|
|
**Type**: `Partial<NuxtHooks>`
|
|
|
|
Hooks to be installed for the module. If provided, the module will install the hooks.
|
|
|
|
- `setup` (optional)
|
|
|
|
**Type**: `(this: void, resolvedOptions: T, nuxt: Nuxt) => Awaitable<void | false | ModuleSetupReturn>`
|
|
|
|
Setup function for the module. If provided, the module will call the setup function.
|
|
|
|
#### Examples
|
|
|
|
```ts
|
|
// https://github.com/nuxt/starter/tree/module
|
|
import { defineNuxtModule } from '@nuxt/kit'
|
|
|
|
export interface ModuleOptions {}
|
|
|
|
export default defineNuxtModule<ModuleOptions>({
|
|
meta: {
|
|
name: 'my-module',
|
|
configKey: 'myModule'
|
|
},
|
|
defaults: {
|
|
test: 123
|
|
},
|
|
setup (options, nuxt) {
|
|
nuxt.hook('modules:done', () => {
|
|
console.log('My module is ready with current test option: ', options.test)
|
|
})
|
|
}
|
|
})
|
|
```
|
|
|
|
|
|
### `installModule`
|
|
|
|
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.
|
|
|
|
#### Type
|
|
|
|
```ts
|
|
async function installModule (moduleToInstall: string | NuxtModule, inlineOptions?: any, nuxt?: Nuxt)
|
|
```
|
|
|
|
#### Parameters
|
|
|
|
##### `moduleToInstall`
|
|
|
|
**Type**: `string` | `NuxtModule`
|
|
|
|
**Required**: `true`
|
|
|
|
The module to install. Can be either a string with the module name or a module object itself.
|
|
|
|
##### `inlineOptions`
|
|
|
|
**Type**: `any`
|
|
|
|
**Default**: `{}`
|
|
|
|
An object with the module options to be passed to the module's `setup` function.
|
|
|
|
##### `nuxt`
|
|
|
|
**Type**: `Nuxt`
|
|
|
|
**Default**: `useNuxt()`
|
|
|
|
Nuxt instance. If not provided, it will be retrieved from the context via `useNuxt()` call.
|
|
|
|
#### Examples
|
|
|
|
```ts
|
|
import { defineNuxtModule, installModule } from '@nuxt/kit'
|
|
|
|
export default defineNuxtModule<ModuleOptions>({
|
|
async setup (options, nuxt) {
|
|
// will install @nuxtjs/fontaine with Roboto font and Impact fallback
|
|
await installModule('@nuxtjs/fontaine', {
|
|
// module configuration
|
|
fonts: [
|
|
{
|
|
family: 'Roboto',
|
|
fallbacks: ['Impact'],
|
|
fallbackName: 'fallback-a',
|
|
}
|
|
]
|
|
})
|
|
}
|
|
})
|
|
```
|
|
|
|
## Programmatic Usage
|
|
|
|
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/loader)
|
|
|
|
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).
|
|
|
|
### `loadNuxt`
|
|
|
|
Load Nuxt programmatically. It will load the Nuxt configuration, instantiate and return the promise with Nuxt instance.
|
|
|
|
#### Type
|
|
|
|
```ts
|
|
async function loadNuxt (loadOptions?: LoadNuxtOptions): Promise<Nuxt>
|
|
|
|
interface LoadNuxtOptions extends LoadNuxtConfigOptions {
|
|
dev?: boolean
|
|
ready?: boolean
|
|
rootDir?: string
|
|
config?: LoadNuxtConfigOptions['overrides']
|
|
}
|
|
```
|
|
|
|
#### Parameters
|
|
|
|
##### `loadOptions`
|
|
|
|
**Type**: `LoadNuxtOptions`
|
|
|
|
**Default**: `{}`
|
|
|
|
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:
|
|
|
|
- `dev` (optional)
|
|
|
|
**Type**: `boolean`
|
|
|
|
**Default**: `false`
|
|
|
|
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.
|
|
|
|
- `rootDir` (optional)
|
|
|
|
**Type**: `string`
|
|
|
|
**Default**: `null`
|
|
|
|
**Deprecated**: Use `cwd` option instead.
|
|
|
|
The root directory of the Nuxt project.
|
|
|
|
- `config` (optional)
|
|
|
|
**Type**: `LoadNuxtConfigOptions['overrides']`
|
|
|
|
**Default**: `{}`
|
|
|
|
**Deprecated**: Use `overrides` option instead.
|
|
|
|
Overrides for the Nuxt configuration.
|
|
|
|
### `buildNuxt`
|
|
|
|
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.
|
|
|
|
#### Type
|
|
|
|
```ts
|
|
async function buildNuxt (nuxt: Nuxt): Promise<any>
|
|
```
|
|
|
|
#### Parameters
|
|
|
|
##### `nuxt`
|
|
|
|
**Type**: `Nuxt`
|
|
|
|
**Required**: `true`
|
|
|
|
Nuxt instance to build. It can be retrieved from the context via `useNuxt()` call.
|
|
|
|
### `loadNuxtConfig`
|
|
|
|
Load Nuxt configuration. It will return the promise with the configuration object.
|
|
|
|
#### Type
|
|
|
|
```ts
|
|
async function loadNuxtConfig (opts: LoadNuxtConfigOptions): Promise<NuxtOptions>
|
|
```
|
|
|
|
#### Parameters
|
|
|
|
##### `opts`
|
|
|
|
**Type**: `LoadNuxtConfigOptions`
|
|
|
|
**Required**: `true`
|
|
|
|
Options to pass in [`c12`](https://github.com/unjs/c12#options) `loadConfig` call.
|
|
|
|
## Compatibility
|
|
|
|
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/compatibility.ts)
|
|
|
|
### `checkNuxtCompatibility`
|
|
|
|
Checks if constraints are met for the current Nuxt version. If not, returns an array of messages. Nuxt 2 version also checks for `bridge` support.
|
|
|
|
#### Type
|
|
|
|
```ts
|
|
async function checkNuxtCompatibility(
|
|
constraints: NuxtCompatibility,
|
|
nuxt?: Nuxt
|
|
): Promise<NuxtCompatibilityIssues>;
|
|
|
|
interface NuxtCompatibility {
|
|
nuxt?: string;
|
|
bridge?: boolean;
|
|
}
|
|
|
|
interface NuxtCompatibilityIssue {
|
|
name: string;
|
|
message: string;
|
|
}
|
|
|
|
interface NuxtCompatibilityIssues extends Array<NuxtCompatibilityIssue> {
|
|
toString(): string;
|
|
}
|
|
```
|
|
|
|
#### Parameters
|
|
|
|
##### `constraints`
|
|
|
|
**Type**: `NuxtCompatibility`
|
|
|
|
**Default**: `{}`
|
|
|
|
Constraints to check for. It accepts the following properties:
|
|
|
|
- `nuxt` (optional)
|
|
|
|
**Type**: `string`
|
|
|
|
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.
|
|
|
|
### `assertNuxtCompatibility`
|
|
|
|
Asserts that constraints are met for the current Nuxt version. If not, throws an error with the list of issues as string.
|
|
|
|
#### Type
|
|
|
|
```ts
|
|
async function assertNuxtCompatibility(
|
|
constraints: NuxtCompatibility,
|
|
nuxt?: Nuxt
|
|
): Promise<true>;
|
|
|
|
interface NuxtCompatibility {
|
|
nuxt?: string;
|
|
bridge?: boolean;
|
|
}
|
|
```
|
|
|
|
#### Parameters
|
|
|
|
##### `constraints`
|
|
|
|
**Type**: `NuxtCompatibility`
|
|
|
|
**Default**: `{}`
|
|
|
|
Constraints to check for. It accepts the following properties:
|
|
|
|
- `nuxt` (optional)
|
|
|
|
**Type**: `string`
|
|
|
|
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:
|
|
|
|
- `nuxt` (optional)
|
|
|
|
**Type**: `string`
|
|
|
|
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.
|
|
|
|
### `isNuxt2`
|
|
|
|
Checks if the current Nuxt version is 2.x.
|
|
|
|
#### Type
|
|
|
|
```ts
|
|
function isNuxt2(nuxt?: Nuxt): boolean;
|
|
```
|
|
|
|
#### Parameters
|
|
|
|
##### `nuxt`
|
|
|
|
**Type**: `Nuxt`
|
|
|
|
**Default**: `useNuxt()`
|
|
|
|
Nuxt instance. If not provided, it will be retrieved from the context via `useNuxt()` call.
|
|
|
|
### `isNuxt3`
|
|
|
|
Checks if the current Nuxt version is 3.x.
|
|
|
|
#### Type
|
|
|
|
```ts
|
|
function isNuxt3(nuxt?: Nuxt): boolean;
|
|
```
|
|
|
|
#### Parameters
|
|
|
|
##### `nuxt`
|
|
|
|
**Type**: `Nuxt`
|
|
|
|
**Default**: `useNuxt()`
|
|
|
|
Nuxt instance. If not provided, it will be retrieved from the context via `useNuxt()` call.
|
|
|
|
### `getNuxtVersion`
|
|
|
|
Returns the current Nuxt version.
|
|
|
|
#### Type
|
|
|
|
```ts
|
|
function getNuxtVersion(nuxt?: Nuxt): string;
|
|
```
|
|
|
|
#### Parameters
|
|
|
|
##### `nuxt`
|
|
|
|
**Type**: `Nuxt`
|
|
|
|
**Default**: `useNuxt()`
|
|
|
|
Nuxt instance. If not provided, it will be retrieved from the context via `useNuxt()` call.
|
|
|
|
## Auto-imports
|
|
|
|
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/imports.ts)
|
|
|
|
### `addImports`
|
|
|
|
Add imports to the Nuxt application. It makes your imports available in the Nuxt application without the need to import them manually.
|
|
|
|
#### Type
|
|
|
|
```ts
|
|
function addImports (imports: Import | Import[]): void
|
|
|
|
interface Import {
|
|
from: string
|
|
priority?: number
|
|
disabled?: boolean
|
|
meta?: {
|
|
description?: string
|
|
docsUrl?: string
|
|
[key: string]: any
|
|
}
|
|
type?: boolean
|
|
typeFrom?: string
|
|
name: string
|
|
as?: string
|
|
}
|
|
```
|
|
|
|
#### Parameters
|
|
|
|
##### `imports`
|
|
|
|
**Type**: `Import | Import[]`
|
|
|
|
**Required**: `true`
|
|
|
|
An object or an array of objects with the following properties:
|
|
|
|
- `from` (required)
|
|
|
|
**Type**: `string`
|
|
|
|
Module specifier to import from.
|
|
|
|
- `priority` (optional)
|
|
|
|
**Type**: `number`
|
|
|
|
**Default**: `1`
|
|
|
|
Priority of the import, if multiple imports have the same name, the one with the highest priority will be used.
|
|
|
|
- `disabled` (optional)
|
|
|
|
**Type**: `boolean`
|
|
|
|
If this import is disabled.
|
|
|
|
- `meta` (optional)
|
|
|
|
**Type**: `object`
|
|
|
|
Metadata of the import.
|
|
|
|
- `meta.description` (optional)
|
|
|
|
**Type**: `string`
|
|
|
|
Short description of the import.
|
|
|
|
- `meta.docsUrl` (optional)
|
|
|
|
**Type**: `string`
|
|
|
|
URL to the documentation.
|
|
|
|
- `meta[key]` (optional)
|
|
|
|
**Type**: `any`
|
|
|
|
Additional metadata.
|
|
|
|
- `type` (optional)
|
|
|
|
**Type**: `boolean`
|
|
|
|
If this import is a pure type import.
|
|
|
|
- `typeFrom` (optional)
|
|
|
|
**Type**: `string`
|
|
|
|
Using this as the from when generating type declarations.
|
|
|
|
- `name` (required)
|
|
|
|
**Type**: `string`
|
|
|
|
Import name to be detected.
|
|
|
|
- `as` (optional)
|
|
|
|
**Type**: `string`
|
|
|
|
Import as this name.
|
|
|
|
#### Examples
|
|
|
|
```ts
|
|
// https://github.com/pi0/storyblok-nuxt
|
|
import { defineNuxtModule, addImports, createResolver } from '@nuxt/kit'
|
|
|
|
export default defineNuxtModule({
|
|
setup(options, nuxt) {
|
|
const names = [
|
|
"useStoryblok",
|
|
"useStoryblokApi",
|
|
"useStoryblokBridge",
|
|
"renderRichText",
|
|
"RichTextSchema"
|
|
];
|
|
|
|
names.forEach((name) =>
|
|
addImports({ name, as: name, from: "@storyblok/vue" })
|
|
);
|
|
}
|
|
})
|
|
```
|
|
|
|
### `addImportsDir`
|
|
|
|
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.
|
|
|
|
#### Type
|
|
|
|
```ts
|
|
function addImportsDir (dirs: string | string[], opts?: { prepend?: boolean })
|
|
```
|
|
|
|
#### Parameters
|
|
|
|
##### `dirs`
|
|
|
|
**Type**: `string | string[]`
|
|
|
|
**Required**: `true`
|
|
|
|
A string or an array of strings with the path to the directory to import from.
|
|
|
|
##### `opts`
|
|
|
|
**Type**: `{ prepend?: boolean }`
|
|
|
|
**Default**: `{}`
|
|
|
|
Options to pass to the import. If `prepend` is set to `true`, the imports will be prepended to the list of imports.
|
|
|
|
#### Examples
|
|
|
|
```ts
|
|
// https://github.com/vueuse/motion/tree/main/src/nuxt
|
|
import { defineNuxtModule, addImportsDir, createResolver } from '@nuxt/kit'
|
|
|
|
export default defineNuxtModule<ModuleOptions>({
|
|
meta: {
|
|
name: '@vueuse/motion',
|
|
configKey: 'motion',
|
|
},
|
|
defaults: {},
|
|
setup(options, nuxt) {
|
|
const { resolve } = createResolver(import.meta.url)
|
|
addImportsDir(resolve('./runtime/composables'))
|
|
},
|
|
})
|
|
```
|
|
|
|
### `addImportsSources`
|
|
|
|
Add listed imports to the Nuxt application.
|
|
|
|
#### Type
|
|
|
|
```ts
|
|
function addImportsSources (importSources: ImportSource | ImportSource[])
|
|
|
|
interface Import {
|
|
from: string
|
|
priority?: number
|
|
disabled?: boolean
|
|
meta?: {
|
|
description?: string
|
|
docsUrl?: string
|
|
[key: string]: any
|
|
}
|
|
type?: boolean
|
|
typeFrom?: string
|
|
name: string
|
|
as?: string
|
|
}
|
|
|
|
interface ImportSource extends Import {
|
|
imports: (PresetImport | ImportSource)[]
|
|
}
|
|
|
|
type PresetImport = Omit<Import, 'from'> | string | [name: string, as?: string, from?: string]
|
|
```
|
|
|
|
#### Parameters
|
|
|
|
##### `importSources`
|
|
|
|
**Type**: `ImportSource | ImportSource[]`
|
|
|
|
**Required**: `true`
|
|
|
|
An object or an array of objects with the following properties:
|
|
|
|
- `imports` (required)
|
|
|
|
**Type**: `PresetImport | ImportSource[]`
|
|
|
|
**Required**: `true`
|
|
|
|
An object or an array of objects, which can be import names, import objects or import sources.
|
|
|
|
- `from` (required)
|
|
|
|
**Type**: `string`
|
|
|
|
Module specifier to import from.
|
|
|
|
- `priority` (optional)
|
|
|
|
**Type**: `number`
|
|
|
|
**Default**: `1`
|
|
|
|
Priority of the import, if multiple imports have the same name, the one with the highest priority will be used.
|
|
|
|
- `disabled` (optional)
|
|
|
|
**Type**: `boolean`
|
|
|
|
If this import is disabled.
|
|
|
|
- `meta` (optional)
|
|
|
|
**Type**: `object`
|
|
|
|
Metadata of the import.
|
|
|
|
- `meta.description` (optional)
|
|
|
|
**Type**: `string`
|
|
|
|
Short description of the import.
|
|
|
|
- `meta.docsUrl` (optional)
|
|
|
|
**Type**: `string`
|
|
|
|
URL to the documentation.
|
|
|
|
- `meta[key]` (optional)
|
|
|
|
**Type**: `any`
|
|
|
|
Additional metadata.
|
|
|
|
- `type` (optional)
|
|
|
|
**Type**: `boolean`
|
|
|
|
If this import is a pure type import.
|
|
|
|
- `typeFrom` (optional)
|
|
|
|
**Type**: `string`
|
|
|
|
Using this as the from when generating type declarations.
|
|
|
|
- `name` (required)
|
|
|
|
**Type**: `string`
|
|
|
|
Import name to be detected.
|
|
|
|
- `as` (optional)
|
|
|
|
**Type**: `string`
|
|
|
|
Import as this name.
|
|
|
|
#### Examples
|
|
|
|
```ts
|
|
// https://github.com/elk-zone/elk
|
|
import { defineNuxtModule, addImportsSources } from '@nuxt/kit'
|
|
|
|
export default defineNuxtModule({
|
|
setup() {
|
|
// add imports from h3 to make them autoimported
|
|
addImportsSources({
|
|
from: 'h3',
|
|
imports: ['defineEventHandler', 'getQuery', 'getRouterParams', 'readBody', 'sendRedirect'] as Array<keyotypeof import('h3')>,
|
|
})
|
|
}
|
|
})
|
|
```
|
|
|
|
## Components
|
|
|
|
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/components.ts)
|
|
|
|
### `addComponentsDir`
|
|
|
|
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
|
|
|
|
interface ComponentsDir {
|
|
path: string
|
|
pattern?: string | string[]
|
|
ignore?: string[]
|
|
prefix?: string
|
|
pathPrefix?: boolean
|
|
enabled?: boolean
|
|
prefetch?: boolean
|
|
preload?: boolean
|
|
isAsync?: boolean
|
|
extendComponent?: (component: Component) => Promise<Component | void> | (Component | void)
|
|
global?: boolean
|
|
island?: boolean
|
|
watch?: boolean
|
|
extensions?: string[]
|
|
transpile?: 'auto' | boolean
|
|
}
|
|
|
|
interface Component {
|
|
pascalName: string
|
|
kebabName: string
|
|
export: string
|
|
filePath: string
|
|
shortPath: string
|
|
chunkName: string
|
|
prefetch: boolean
|
|
preload: boolean
|
|
global?: boolean
|
|
island?: boolean
|
|
mode?: 'client' | 'server' | 'all'
|
|
priority?: number
|
|
}
|
|
```
|
|
|
|
#### Parameters
|
|
|
|
##### `dir`
|
|
|
|
**Type**: `ComponentsDir`
|
|
|
|
**Required**: `true`
|
|
|
|
An object with the following properties:
|
|
|
|
- `path` (required)
|
|
|
|
**Type**: `string`
|
|
|
|
Path (absolute or relative) to the directory containing your components.
|
|
You can use Nuxt aliases (~ or @) to refer to directories inside project or directly use an npm package path similar to require.
|
|
|
|
- `pattern` (optional)
|
|
|
|
**Type**: `string | string[]`
|
|
|
|
Accept Pattern that will be run against specified path.
|
|
|
|
- `ignore` (optional)
|
|
|
|
**Type**: `string[]`
|
|
|
|
Ignore patterns that will be run against specified path.
|
|
|
|
- `prefix` (optional)
|
|
|
|
**Type**: `string`
|
|
|
|
Prefix all matched components with this string.
|
|
|
|
- `pathPrefix` (optional)
|
|
|
|
**Type**: `boolean`
|
|
|
|
Prefix component name by its path.
|
|
|
|
- `enabled` (optional)
|
|
|
|
**Type**: `boolean`
|
|
|
|
Ignore scanning this directory if set to `true`.
|
|
|
|
- `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)
|
|
|
|
- `isAsync` (optional)
|
|
|
|
**Type**: `boolean`
|
|
|
|
This flag indicates, component should be loaded async (with a separate chunk) regardless of using Lazy prefix or not.
|
|
|
|
- `extendComponent` (optional)
|
|
|
|
**Type**: `(component: Component) => Promise<Component | void> | (Component | 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.
|
|
|
|
### `addComponent`
|
|
|
|
Register a component to be automatically imported.
|
|
|
|
#### Type
|
|
|
|
```ts
|
|
async function addComponent (opts: AddComponentOptions): void
|
|
|
|
interface AddComponentOptions {
|
|
name: string,
|
|
filePath: string,
|
|
pascalName?: string,
|
|
kebabName?: string,
|
|
export?: string,
|
|
shortPath?: string,
|
|
chunkName?: string,
|
|
prefetch?: boolean,
|
|
preload?: boolean,
|
|
global?: boolean,
|
|
island?: boolean,
|
|
mode?: 'client' | 'server' | 'all',
|
|
priority?: number,
|
|
}
|
|
```
|
|
|
|
#### Parameters
|
|
|
|
##### `opts`
|
|
|
|
**Type**: `AddComponentOptions`
|
|
|
|
**Required**: `true`
|
|
|
|
An object with the following properties:
|
|
|
|
- `name` (required)
|
|
|
|
**Type**: `string`
|
|
|
|
Component name.
|
|
|
|
- `filePath` (required)
|
|
|
|
**Type**: `string`
|
|
|
|
Path to the component.
|
|
|
|
- `pascalName` (optional)
|
|
|
|
**Type**: `pascalCase(opts.name)`
|
|
|
|
Pascal case component name. If not provided, it will be generated from the component name.
|
|
|
|
- `kebabName` (optional)
|
|
|
|
**Type**: `kebabCase(opts.name)`
|
|
|
|
Kebab case component name. If not provided, it will be generated from the component name.
|
|
|
|
- `export` (optional)
|
|
|
|
**Type**: `string`
|
|
|
|
**Default**: `'default'`
|
|
|
|
Specify named or default export. If not provided, it will be set to `'default'`.
|
|
|
|
- `shortPath` (optional)
|
|
|
|
**Type**: `string`
|
|
|
|
Short path to the component. If not provided, it will be generated from the component path.
|
|
|
|
- `chunkName` (optional)
|
|
|
|
**Type**: `string`
|
|
|
|
**Default**: `'components/' + kebabCase(opts.name)`
|
|
|
|
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.
|
|
|
|
## Context
|
|
|
|
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/context.ts)
|
|
|
|
::alert{type=info}
|
|
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()`. However, if you want to access Nuxt from other functions, then you can use `useNuxt()` or `tryUseNuxt()`. You can look at [Nuxt Site Config](https://github.com/harlan-zw/nuxt-site-config) as an example of usage.
|
|
::
|
|
|
|
### `useNuxt`
|
|
|
|
Get the Nuxt instance from the context. It will throw an error if Nuxt is not available.
|
|
|
|
#### Type
|
|
|
|
```ts
|
|
function useNuxt(): Nuxt
|
|
|
|
interface Nuxt {
|
|
options: NuxtOptions
|
|
hooks: Hookable<NuxtHooks>
|
|
hook: Nuxt['hooks']['hook']
|
|
callHook: Nuxt['hooks']['callHook']
|
|
addHooks: Nuxt['hooks']['addHooks']
|
|
ready: () => Promise<void>
|
|
close: () => Promise<void>
|
|
server?: any
|
|
vfs: Record<string, string>
|
|
apps: Record<string, NuxtApp>
|
|
}
|
|
```
|
|
|
|
#### Examples
|
|
|
|
::code-group
|
|
|
|
```ts [setupTranspilation.ts]
|
|
// https://github.com/Lexpeartha/nuxt-xstate/blob/main/src/parts/transpile.ts
|
|
import { useNuxt } from '@nuxt/kit'
|
|
|
|
export const setupTranspilation = () => {
|
|
const nuxt = useNuxt()
|
|
|
|
nuxt.options.build.transpile = nuxt.options.build.transpile || []
|
|
|
|
if (nuxt.options.builder === '@nuxt/webpack-builder') {
|
|
nuxt.options.build.transpile.push(
|
|
'xstate',
|
|
)
|
|
}
|
|
}
|
|
```
|
|
|
|
```ts [module.ts]
|
|
import { useNuxt } from '@nuxt/kit'
|
|
import { setupTranspilation } from './setupTranspilation'
|
|
|
|
export default defineNuxtModule({
|
|
setup() {
|
|
setupTranspilation()
|
|
}
|
|
})
|
|
```
|
|
|
|
::
|
|
|
|
### `tryUseNuxt`
|
|
|
|
Get the Nuxt instance from the context. It will return `null` if Nuxt is not available.
|
|
|
|
#### Type
|
|
|
|
```ts
|
|
function tryUseNuxt(): Nuxt | null
|
|
|
|
interface Nuxt {
|
|
options: NuxtOptions
|
|
hooks: Hookable<NuxtHooks>
|
|
hook: Nuxt['hooks']['hook']
|
|
callHook: Nuxt['hooks']['callHook']
|
|
addHooks: Nuxt['hooks']['addHooks']
|
|
ready: () => Promise<void>
|
|
close: () => Promise<void>
|
|
server?: any
|
|
vfs: Record<string, string>
|
|
apps: Record<string, NuxtApp>
|
|
}
|
|
```
|
|
|
|
#### Examples
|
|
|
|
::code-group
|
|
|
|
```ts [requireSiteConfig.ts]
|
|
// https://github.com/harlan-zw/nuxt-site-config/blob/main/test/assertions.test.ts
|
|
import { tryUseNuxt } from '@nuxt/kit'
|
|
|
|
interface SiteConfig {
|
|
title: string
|
|
}
|
|
|
|
export const requireSiteConfig = (): SiteConfig => {
|
|
const nuxt = tryUseNuxt()
|
|
if (!nuxt) {
|
|
return { title: null }
|
|
}
|
|
return nuxt.options.siteConfig
|
|
}
|
|
```
|
|
|
|
```ts [module.ts]
|
|
import { useNuxt } from '@nuxt/kit'
|
|
import { requireSiteConfig } from './requireSiteConfig'
|
|
|
|
export default defineNuxtModule({
|
|
setup(_, nuxt) {
|
|
const config = requireSiteConfig()
|
|
nuxt.options.app.head.title = config.title
|
|
}
|
|
})
|
|
```
|
|
|
|
::
|
|
|
|
## Pages
|
|
|
|
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/pages.ts)
|
|
|
|
### `extendPages`
|
|
|
|
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.
|
|
|
|
#### Type
|
|
|
|
```ts
|
|
function extendPages (callback: (pages: NuxtPage[]) => void) => void
|
|
|
|
type NuxtPage = {
|
|
name?: string
|
|
path: string
|
|
file?: string
|
|
meta?: Record<string, any>
|
|
alias?: string[] | string
|
|
redirect?: RouteLocationRaw
|
|
children?: NuxtPage[]
|
|
}
|
|
```
|
|
|
|
#### Parameters
|
|
|
|
##### `callback`
|
|
|
|
**Type**: `(pages: NuxtPage[]) => void`
|
|
|
|
**Required**: `true`
|
|
|
|
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.
|
|
|
|
#### Examples
|
|
|
|
```ts
|
|
// https://github.com/nuxt-modules/prismic/blob/master/src/module.ts
|
|
import { createResolver, defineNuxtModule, extendPages } from '@nuxt/kit'
|
|
|
|
export default defineNuxtModule({
|
|
setup(options) {
|
|
const resolver = createResolver(import.meta.url)
|
|
|
|
extendPages((pages) => {
|
|
pages.unshift({
|
|
name: 'prismic-preview',
|
|
path: '/preview',
|
|
file: resolver.resolve('runtime/preview.vue')
|
|
})
|
|
})
|
|
}
|
|
})
|
|
```
|
|
|
|
- `extendRouteRules (route: string, rule: NitroRouteConfig, options: ExtendRouteRulesOptions)`
|
|
- `addRouteMiddleware (input: NuxtMiddleware | NuxtMiddleware[], options: AddRouteMiddlewareOptions)`
|
|
|
|
## Plugins
|
|
|
|
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/plugin.ts)
|
|
|
|
- `addPlugin(pluginOptions, { append? })`
|
|
- `addPluginTemplate(pluginOptions, { append? })`
|
|
|
|
## Templates
|
|
|
|
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/template.ts)
|
|
|
|
- `addTemplate(templateOptions)`
|
|
- `addTypeTemplate(templateOptions)`
|
|
- `updateTemplates({ filter?: ResolvedNuxtTemplate => boolean })`
|
|
|
|
## Nitro
|
|
|
|
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/nitro.ts)
|
|
|
|
- `addServerHandler (handler)`
|
|
- `addDevServerHandler (handler)`
|
|
- `useNitro()` (only usable after `ready` hook)
|
|
- `addServerPlugin`
|
|
- `addPrerenderRoutes`
|
|
|
|
## Resolving
|
|
|
|
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/resolve.ts)
|
|
|
|
- `resolvePath (path, resolveOptions?)`
|
|
- `resolveAlias (path, aliases?)`
|
|
- `findPath (paths, resolveOptions?)`
|
|
- `createResolver (base)`
|
|
|
|
## Logging
|
|
|
|
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/logger.ts)
|
|
|
|
- `useLogger(scope?)`
|
|
|
|
## Builder
|
|
|
|
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/build.ts)
|
|
|
|
- `extendWebpackConfig(callback, options?)`
|
|
- `extendViteConfig(callback, options?)`
|
|
- `addWebpackPlugin(webpackPlugin, options?)`
|
|
- `addVitePlugin(vitePlugin, options?)`
|
|
|
|
## Examples
|
|
|
|
### Accessing Nuxt Vite Config
|
|
|
|
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.
|
|
|
|
Some examples of projects doing this already:
|
|
|
|
- [histoire](https://github.com/histoire-dev/histoire/blob/main/packages/histoire-plugin-nuxt/src/index.ts)
|
|
- [nuxt-vitest](https://github.com/danielroe/nuxt-vitest/blob/main/packages/nuxt-vitest/src/config.ts)
|
|
- [@storybook-vue/nuxt](https://github.com/storybook-vue/nuxt/blob/main/src/preset.ts)
|
|
|
|
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.
|
|
|
|
```js
|
|
import { loadNuxt, buildNuxt } from '@nuxt/kit'
|
|
|
|
// https://github.com/nuxt/nuxt/issues/14534
|
|
async function getViteConfig() {
|
|
const nuxt = await loadNuxt({ cwd: process.cwd(), dev: false, overrides: { ssr: false } })
|
|
return new Promise((resolve, reject) => {
|
|
nuxt.hook('vite:extendConfig', (config, { isClient }) => {
|
|
if (isClient) {
|
|
resolve(config)
|
|
throw new Error('_stop_')
|
|
}
|
|
})
|
|
buildNuxt(nuxt).catch((err) => {
|
|
if (!err.toString().includes('_stop_')) {
|
|
reject(err)
|
|
}
|
|
})
|
|
}).finally(() => nuxt.close())
|
|
}
|
|
|
|
const viteConfig = await getViteConfig()
|
|
console.log(viteConfig)
|
|
```
|