mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-22 05:35:13 +00:00
docs: improve nuxt kit
section (#22375)
This commit is contained in:
parent
b3d3d7f4fd
commit
2e02e2c5b1
@ -1,154 +0,0 @@
|
||||
---
|
||||
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"}
|
||||
::
|
||||
|
||||
## Utilities
|
||||
|
||||
### Modules
|
||||
|
||||
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/module)
|
||||
|
||||
- `installModule(module, inlineOptions)`
|
||||
|
||||
### Programmatic Usage
|
||||
|
||||
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/loader)
|
||||
|
||||
- `loadNuxt(loadOptions)`
|
||||
- `buildNuxt(nuxt)`
|
||||
- `loadNuxtConfig(loadOptions)`
|
||||
|
||||
### Compatibility
|
||||
|
||||
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/compatibility.ts)
|
||||
|
||||
- `checkNuxtCompatibility(constraints)`
|
||||
- `assertNuxtCompatibility(constraints)`
|
||||
- `hasNuxtCompatibility(constraints)`
|
||||
- `isNuxt2()`
|
||||
- `isNuxt3()`
|
||||
- `getNuxtVersion()`
|
||||
|
||||
### Auto-imports
|
||||
|
||||
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/imports.ts)
|
||||
|
||||
- `addImports(imports)`
|
||||
- `addImportsDir(importDirs, { prepend? })`
|
||||
- `addImportsSources(importSources)`
|
||||
|
||||
### Components
|
||||
|
||||
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/components.ts)
|
||||
|
||||
- `addComponentsDir(dir)`
|
||||
- `addComponent(componentObject)`
|
||||
|
||||
### Context
|
||||
|
||||
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/context.ts)
|
||||
|
||||
- `useNuxt()`
|
||||
- `tryUseNuxt()`
|
||||
|
||||
### Pages
|
||||
|
||||
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/pages.ts)
|
||||
|
||||
- `extendPages (callback: pages => void)`
|
||||
- `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/storybook-nuxt/blob/main/packages/storybook-nuxt/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)
|
||||
```
|
170
docs/3.api/4.kit/1.modules.md
Normal file
170
docs/3.api/4.kit/1.modules.md
Normal file
@ -0,0 +1,170 @@
|
||||
---
|
||||
title: "Modules"
|
||||
description: 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.
|
||||
---
|
||||
# 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. For example, you can use the `defineNuxtModule` function to define a module and the `installModule` function to install a module programmatically.
|
||||
|
||||
## `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 default defineNuxtModule({
|
||||
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({
|
||||
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',
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
})
|
||||
```
|
281
docs/3.api/4.kit/10.templates.md
Normal file
281
docs/3.api/4.kit/10.templates.md
Normal file
@ -0,0 +1,281 @@
|
||||
---
|
||||
title: "Templates"
|
||||
description: Nuxt Kit provides a set of utilities to help you work with templates. These functions allow you to generate extra files during development and build time.
|
||||
---
|
||||
|
||||
# Templates
|
||||
|
||||
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/template.ts)
|
||||
|
||||
Templates allows to generate extra files during development and build time. These files will be available in virtual filesystem and can be used in plugins, layouts, components, etc. `addTemplate` and `addTypeTemplate` allow you to add templates to the Nuxt application. `updateTemplates` allows you to regenerate templates that match the filter.
|
||||
|
||||
## `addTemplate`
|
||||
|
||||
Renders given template during build into the project buildDir.
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function addTemplate (template: NuxtTemplate | string): ResolvedNuxtTemplate
|
||||
|
||||
interface NuxtTemplate {
|
||||
src?: string
|
||||
filename?: string
|
||||
dst?: string
|
||||
options?: Record<string, any>
|
||||
getContents?: (data: Record<string, any>) => string | Promise<string>
|
||||
write?: boolean
|
||||
}
|
||||
|
||||
interface ResolvedNuxtTemplate {
|
||||
src: string
|
||||
filename: string
|
||||
dst: string
|
||||
options: Record<string, any>
|
||||
getContents: (data: Record<string, any>) => string | Promise<string>
|
||||
write: boolean
|
||||
filename: string
|
||||
dst: string
|
||||
}
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `template`
|
||||
|
||||
**Type**: `NuxtTemplate | string`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
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.
|
||||
|
||||
- `options` (optional)
|
||||
|
||||
**Type**: `Options`
|
||||
|
||||
Options to pass to the template.
|
||||
|
||||
- `getContents` (optional)
|
||||
|
||||
**Type**: `(data: Options) => string | Promise<string>`
|
||||
|
||||
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.
|
||||
|
||||
### Examples
|
||||
|
||||
::code-group
|
||||
|
||||
```ts [module.ts]
|
||||
// https://github.com/nuxt/bridge
|
||||
import { addTemplate, defineNuxtModule } from '@nuxt/kit'
|
||||
import { defu } from 'defu'
|
||||
|
||||
export default defineNuxtModule({
|
||||
setup(options, nuxt) {
|
||||
const globalMeta = defu(nuxt.options.app.head, {
|
||||
charset: options.charset,
|
||||
viewport: options.viewport
|
||||
})
|
||||
|
||||
addTemplate({
|
||||
filename: 'meta.config.mjs',
|
||||
getContents: () => 'export default ' + JSON.stringify({ globalMeta, mixinKey: 'setup' })
|
||||
})
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
```ts [plugin.ts]
|
||||
import { createHead as createClientHead, createServerHead } from '@unhead/vue'
|
||||
import { defineNuxtPlugin } from '#app'
|
||||
// @ts-ignore
|
||||
import metaConfig from '#build/meta.config.mjs'
|
||||
|
||||
export default defineNuxtPlugin((nuxtApp) => {
|
||||
const createHead = process.server ? createServerHead : createClientHead
|
||||
const head = createHead()
|
||||
head.push(metaConfig.globalMeta)
|
||||
|
||||
nuxtApp.vueApp.use(head)
|
||||
})
|
||||
```
|
||||
|
||||
::
|
||||
|
||||
## `addTypeTemplate`
|
||||
|
||||
Renders given template during build into the project buildDir, then registers it as types.
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function addTypeTemplate (template: NuxtTypeTemplate | string): ResolvedNuxtTemplate
|
||||
|
||||
interface NuxtTemplate {
|
||||
src?: string
|
||||
filename?: string
|
||||
dst?: string
|
||||
options?: Record<string, any>
|
||||
getContents?: (data: Record<string, any>) => string | Promise<string>
|
||||
}
|
||||
|
||||
interface ResolvedNuxtTemplate {
|
||||
src: string
|
||||
filename: string
|
||||
dst: string
|
||||
options: Record<string, any>
|
||||
getContents: (data: Record<string, any>) => string | Promise<string>
|
||||
write: boolean
|
||||
filename: string
|
||||
dst: string
|
||||
}
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `template`
|
||||
|
||||
**Type**: `NuxtTypeTemplate | string`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
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.
|
||||
|
||||
- `options` (optional)
|
||||
|
||||
**Type**: `Options`
|
||||
|
||||
Options to pass to the template.
|
||||
|
||||
- `getContents` (optional)
|
||||
|
||||
**Type**: `(data: Options) => string | Promise<string>`
|
||||
|
||||
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.
|
||||
|
||||
### Examples
|
||||
|
||||
```ts
|
||||
// https://github.com/Hebilicious/nuxtpress
|
||||
import { addTypeTemplate, defineNuxtModule } from "@nuxt/kit"
|
||||
|
||||
export default defineNuxtModule({
|
||||
setup() {
|
||||
addTypeTemplate({
|
||||
filename: "types/markdown.d.ts",
|
||||
getContents: () => /* ts */`
|
||||
declare module '*.md' {
|
||||
import type { ComponentOptions } from 'vue'
|
||||
const Component: ComponentOptions
|
||||
export default Component
|
||||
}`
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## `updateTemplates`
|
||||
|
||||
Regenerate templates that match the filter. If no filter is provided, all templates will be regenerated.
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
async function updateTemplates (options: UpdateTemplatesOptions): void
|
||||
|
||||
interface UpdateTemplatesOptions {
|
||||
filter?: (template: ResolvedNuxtTemplate) => boolean
|
||||
}
|
||||
|
||||
interface ResolvedNuxtTemplate {
|
||||
src: string
|
||||
filename: string
|
||||
dst: string
|
||||
options: Record<string, any>
|
||||
getContents: (data: Record<string, any>) => string | Promise<string>
|
||||
write: boolean
|
||||
filename: string
|
||||
dst: string
|
||||
}
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `options`
|
||||
|
||||
**Type**: `UpdateTemplatesOptions`
|
||||
|
||||
**Default**: `{}`
|
||||
|
||||
Options to pass to the template. This object can have the following property:
|
||||
|
||||
- `filter` (optional)
|
||||
|
||||
**Type**: `(template: ResolvedNuxtTemplate) => boolean`
|
||||
|
||||
A function that will be called with the `template` object. It should return a boolean indicating whether the template should be regenerated. If `filter` is not provided, all templates will be regenerated.
|
||||
|
||||
### Example
|
||||
|
||||
```ts
|
||||
// https://github.com/nuxt/nuxt
|
||||
import { defineNuxtModule, updateTemplates } from '@nuxt/kit'
|
||||
|
||||
export default defineNuxtModule({
|
||||
setup(options, nuxt) {
|
||||
// watch and rebuild routes template list when one of the pages changes
|
||||
nuxt.hook('builder:watch', async (event, relativePath) => {
|
||||
if (event === 'change') { return }
|
||||
|
||||
const path = resolve(nuxt.options.srcDir, relativePath)
|
||||
if (updateTemplatePaths.some(dir => path.startsWith(dir))) {
|
||||
await updateTemplates({
|
||||
filter: template => template.filename === 'routes.mjs'
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
```
|
359
docs/3.api/4.kit/11.nitro.md
Normal file
359
docs/3.api/4.kit/11.nitro.md
Normal file
@ -0,0 +1,359 @@
|
||||
---
|
||||
title: "Nitro"
|
||||
description: Nuxt Kit provides a set of utilities to help you work with Nitro. These functions allow you to add server handlers, plugins, and prerender routes.
|
||||
---
|
||||
|
||||
# Nitro
|
||||
|
||||
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/nitro.ts)
|
||||
|
||||
Nitro is an open source TypeScript framework to build ultra-fast web servers. Nuxt 3 (and, optionally, Nuxt Bridge) uses Nitro as its server engine. You can use `useNitro` to access the Nitro instance, `addServerHandler` to add a server handler, `addDevServerHandler` to add a server handler to be used only in development mode, `addServerPlugin` to add a plugin to extend Nitro's runtime behavior, and `addPrerenderRoutes` to add routes to be prerendered by Nitro.
|
||||
|
||||
## `addServerHandler`
|
||||
|
||||
Adds a nitro server handler. Use it if you want to create server middleware or custom route.
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function addServerHandler (handler: NitroEventHandler): void
|
||||
|
||||
export interface NitroEventHandler {
|
||||
handler: string;
|
||||
route?: string;
|
||||
middleware?: boolean;
|
||||
lazy?: boolean;
|
||||
method?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `handler`
|
||||
|
||||
**Type**: `NitroEventHandler`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
A handler object with the following properties:
|
||||
|
||||
- `handler` (required)
|
||||
|
||||
**Type**: `string`
|
||||
|
||||
Path to event handler.
|
||||
|
||||
- `route` (optional)
|
||||
|
||||
**Type**: `string`
|
||||
|
||||
Path prefix or route. If an empty string used, will be used as a middleware.
|
||||
|
||||
- `middleware` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
Specifies this is a middleware handler. Middleware are called on every route and should normally return nothing to pass to the next handlers.
|
||||
|
||||
- `lazy` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
Use lazy loading to import handler.
|
||||
|
||||
- `method` (optional)
|
||||
|
||||
**Type**: `string`
|
||||
|
||||
Router method matcher. If handler name contains method name, it will be used as a default value.
|
||||
|
||||
### Examples
|
||||
|
||||
::code-group
|
||||
|
||||
```ts [module.ts]
|
||||
// https://github.com/nuxt-modules/robots
|
||||
import { createResolver, defineNuxtModule, addServerHandler } from '@nuxt/kit'
|
||||
|
||||
export default defineNuxtModule({
|
||||
setup(options) {
|
||||
const resolver = createResolver(import.meta.url)
|
||||
|
||||
addServerHandler({
|
||||
route: '/robots.txt'
|
||||
handler: resolver.resolve('./runtime/robots.get.ts')
|
||||
})
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
```ts [runtime/robots.get.ts]
|
||||
export default defineEventHandler(() => {
|
||||
return {
|
||||
body: `User-agent: *\nDisallow: /`
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
::
|
||||
|
||||
## `addDevServerHandler`
|
||||
|
||||
Adds a nitro server handler to be used only in development mode. This handler will be excluded from production build.
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function addDevServerHandler (handler: NitroEventHandler): void
|
||||
|
||||
export interface NitroEventHandler {
|
||||
handler: string;
|
||||
route?: string;
|
||||
middleware?: boolean;
|
||||
lazy?: boolean;
|
||||
method?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `handler`
|
||||
|
||||
**Type**: `NitroEventHandler`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
A handler object with the following properties:
|
||||
|
||||
- `handler` (required)
|
||||
|
||||
**Type**: `string`
|
||||
|
||||
Path to event handler.
|
||||
|
||||
- `route` (optional)
|
||||
|
||||
**Type**: `string`
|
||||
|
||||
Path prefix or route. If an empty string used, will be used as a middleware.
|
||||
|
||||
- `middleware` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
Specifies this is a middleware handler. Middleware are called on every route and should normally return nothing to pass to the next handlers.
|
||||
|
||||
- `lazy` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
Use lazy loading to import handler.
|
||||
|
||||
- `method` (optional)
|
||||
|
||||
**Type**: `string`
|
||||
|
||||
Router method matcher.
|
||||
|
||||
### Examples
|
||||
|
||||
::code-group
|
||||
|
||||
```ts [module.ts]
|
||||
import { createResolver, defineNuxtModule, addDevServerHandler } from '@nuxt/kit'
|
||||
|
||||
export default defineNuxtModule({
|
||||
setup() {
|
||||
const resolver = createResolver(import.meta.url)
|
||||
|
||||
addDevServerHandler({
|
||||
handler: resolver.resolve('./runtime/uptime.get'),
|
||||
route: '/_handler'
|
||||
})
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
```ts [runtime/timer.get.ts]
|
||||
export default defineEventHandler(() => {
|
||||
return {
|
||||
body: `Response generated at ${new Date().toISOString()}`
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
::
|
||||
|
||||
```ts
|
||||
// https://github.com/nuxt-modules/tailwindcss
|
||||
import { joinURL } from 'ufo'
|
||||
import { defineNuxtModule, addDevServerHandler } from '@nuxt/kit'
|
||||
|
||||
export default defineNuxtModule({
|
||||
async setup(options) {
|
||||
const route = joinURL(nuxt.options.app?.baseURL, '/_tailwind')
|
||||
|
||||
// @ts-ignore
|
||||
const createServer = await import('tailwind-config-viewer/server/index.js').then(r => r.default || r) as any
|
||||
const viewerDevMiddleware = createServer({ tailwindConfigProvider: () => options, routerPrefix: route }).asMiddleware()
|
||||
|
||||
addDevServerHandler({ route, handler: viewerDevMiddleware })
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## `useNitro`
|
||||
|
||||
Returns the Nitro instance.
|
||||
|
||||
::alert{type=warning}
|
||||
You can call `useNitro()` only after `ready` hook.
|
||||
::
|
||||
|
||||
::alert{type=info}
|
||||
Changes to the Nitro instance configuration are not applied.
|
||||
::
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function useNitro (): Nitro
|
||||
|
||||
export interface Nitro {
|
||||
options: NitroOptions;
|
||||
scannedHandlers: NitroEventHandler[];
|
||||
vfs: Record<string, string>;
|
||||
hooks: Hookable<NitroHooks>;
|
||||
unimport?: Unimport;
|
||||
logger: ConsolaInstance;
|
||||
storage: Storage;
|
||||
close: () => Promise<void>;
|
||||
updateConfig: (config: NitroDynamicConfig) => void | Promise<void>;
|
||||
}
|
||||
```
|
||||
|
||||
### Examples
|
||||
|
||||
```ts
|
||||
// https://github.com/nuxt/nuxt/blob/4e05650cde31ca73be4d14b1f0d23c7854008749/packages/nuxt/src/core/nuxt.ts#L404
|
||||
import { defineNuxtModule, useNitro, addPlugin, createResolver } from '@nuxt/kit'
|
||||
|
||||
export default defineNuxtModule({
|
||||
setup(options, nuxt) {
|
||||
const resolver = createResolver(import.meta.url)
|
||||
|
||||
nuxt.hook('ready', () => {
|
||||
const nitro = useNitro()
|
||||
if (nitro.options.static && nuxt.options.experimental.payloadExtraction === undefined) {
|
||||
console.warn('Using experimental payload extraction for full-static output. You can opt-out by setting `experimental.payloadExtraction` to `false`.')
|
||||
nuxt.options.experimental.payloadExtraction = true
|
||||
}
|
||||
nitro.options.replace['process.env.NUXT_PAYLOAD_EXTRACTION'] = String(!!nuxt.options.experimental.payloadExtraction)
|
||||
nitro.options._config.replace!['process.env.NUXT_PAYLOAD_EXTRACTION'] = String(!!nuxt.options.experimental.payloadExtraction)
|
||||
|
||||
if (!nuxt.options.dev && nuxt.options.experimental.payloadExtraction) {
|
||||
addPlugin(resolver.resolve(nuxt.options.appDir, 'plugins/payload.client'))
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## `addServerPlugin`
|
||||
|
||||
Add plugin to extend Nitro's runtime behavior.
|
||||
|
||||
::alert{type=info}
|
||||
You can read more about Nitro plugins in the [Nitro documentation](https://nitro.unjs.io/guide/plugins).
|
||||
::
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function addServerPlugin (plugin: string): void
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `plugin`
|
||||
|
||||
**Type**: `string`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
Path to the plugin. The plugin must export a function that accepts Nitro instance as an argument.
|
||||
|
||||
### Examples
|
||||
|
||||
::code-group
|
||||
|
||||
```ts [module.ts]
|
||||
import { createResolver, defineNuxtModule, addServerPlugin } from '@nuxt/kit'
|
||||
|
||||
export default defineNuxtModule({
|
||||
setup() {
|
||||
const resolver = createResolver(import.meta.url)
|
||||
addServerPlugin(resolver.resolve('./runtime/plugin.ts'))
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
```ts [runtime/plugin.ts]
|
||||
export default defineNitroPlugin((nitroApp) => {
|
||||
nitroApp.hooks.hook("request", (event) => {
|
||||
console.log("on request", event.path);
|
||||
});
|
||||
|
||||
nitroApp.hooks.hook("beforeResponse", (event, { body }) => {
|
||||
console.log("on response", event.path, { body });
|
||||
});
|
||||
|
||||
nitroApp.hooks.hook("afterResponse", (event, { body }) => {
|
||||
console.log("on after response", event.path, { body });
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
::
|
||||
|
||||
## `addPrerenderRoutes`
|
||||
|
||||
Add routes to be prerendered to Nitro.
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function function addPrerenderRoutes (routes: string | string[]): void
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `routes`
|
||||
|
||||
**Type**: `string | string[]`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
A route or an array of routes to prerender.
|
||||
|
||||
### Examples
|
||||
|
||||
```ts
|
||||
import { defineNuxtModule, prerenderRoutes } from '@nuxt/kit'
|
||||
|
||||
export default defineNuxtModule({
|
||||
meta: {
|
||||
name: 'nuxt-sitemap',
|
||||
configKey: 'sitemap',
|
||||
},
|
||||
defaults: {
|
||||
sitemapUrl: '/sitemap.xml',
|
||||
prerender: true,
|
||||
},
|
||||
setup(options) {
|
||||
if (options.prerender) {
|
||||
prerenderRoutes(options.sitemapUrl)
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
263
docs/3.api/4.kit/12.resolving.md
Normal file
263
docs/3.api/4.kit/12.resolving.md
Normal file
@ -0,0 +1,263 @@
|
||||
---
|
||||
title: Resolving
|
||||
description: Nuxt Kit provides a set of utilities to help you resolve paths. These functions allow you to resolve paths relative to the current module, with unknown name or extension.
|
||||
---
|
||||
|
||||
# Resolving
|
||||
|
||||
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/resolve.ts)
|
||||
|
||||
Sometimes you need to resolve a paths: relative to the current module, with unknown name or extension. For example, you may want to add a plugin that is located in the same directory as the module. To handle this cases, nuxt provides a set of utilities to resolve paths. `resolvePath` and `resolveAlias` are used to resolve paths relative to the current module. `findPath` is used to find first existing file in given paths. `createResolver` is used to create resolver relative to base path.
|
||||
|
||||
## `resolvePath`
|
||||
|
||||
Resolves full path to a file or directory respecting Nuxt alias and extensions options. If path could not be resolved, normalized input path will be returned.
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
async function resolvePath (path: string, options?: ResolvePathOptions): Promise<string>
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `path`
|
||||
|
||||
**Type**: `string`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
Path to resolve.
|
||||
|
||||
#### `options`
|
||||
|
||||
**Type**: `ResolvePathOptions`
|
||||
|
||||
**Default**: `{}`
|
||||
|
||||
Options to pass to the resolver. This object can have the following properties:
|
||||
|
||||
- `cwd` (optional)
|
||||
|
||||
**Type**: `string`
|
||||
|
||||
**Default**: `process.cwd()`
|
||||
|
||||
Current working directory.
|
||||
|
||||
- `alias` (optional)
|
||||
|
||||
**Type**: `Record<string, string>`
|
||||
|
||||
**Default**: `{}`
|
||||
|
||||
Alias map.
|
||||
|
||||
- `extensions` (optional)
|
||||
|
||||
**Type**: `string[]`
|
||||
|
||||
**Default**: `['.js', '.mjs', '.ts', '.jsx', '.tsx', '.json']`
|
||||
|
||||
Extensions to try.
|
||||
|
||||
### Examples
|
||||
|
||||
```ts
|
||||
// https://github.com/P4sca1/nuxt-headlessui
|
||||
import { defineNuxtModule, resolvePath } from '@nuxt/kit'
|
||||
import { join } from 'pathe'
|
||||
|
||||
const headlessComponents: ComponentGroup[] = [
|
||||
{
|
||||
relativePath: 'combobox/combobox.js',
|
||||
chunkName: 'headlessui/combobox',
|
||||
exports: [
|
||||
'Combobox',
|
||||
'ComboboxLabel',
|
||||
'ComboboxButton',
|
||||
'ComboboxInput',
|
||||
'ComboboxOptions',
|
||||
'ComboboxOption'
|
||||
]
|
||||
},
|
||||
]
|
||||
|
||||
export default defineNuxtModule({
|
||||
meta: {
|
||||
name: 'nuxt-headlessui',
|
||||
configKey: 'headlessui',
|
||||
},
|
||||
defaults: {
|
||||
prefix: 'Headless'
|
||||
},
|
||||
async setup (options) {
|
||||
const entrypoint = await resolvePath('@headlessui/vue')
|
||||
const root = join(entrypoint, '../components')
|
||||
|
||||
for (const group of headlessComponents) {
|
||||
for (const e of group.exports) {
|
||||
addComponent(
|
||||
{
|
||||
name: e,
|
||||
export: e,
|
||||
filePath: join(root, group.relativePath),
|
||||
chunkName: group.chunkName,
|
||||
mode: 'all'
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## `resolveAlias`
|
||||
|
||||
Resolves path aliases respecting Nuxt alias options.
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function resolveAlias (path: string, alias?: Record<string, string>): string
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `path`
|
||||
|
||||
**Type**: `string`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
Path to resolve.
|
||||
|
||||
#### `alias`
|
||||
|
||||
**Type**: `Record<string, string>`
|
||||
|
||||
**Default**: `{}`
|
||||
|
||||
Alias map. If not provided, it will be read from `nuxt.options.alias`.
|
||||
|
||||
## `findPath`
|
||||
|
||||
Try to resolve first existing file in given paths.
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
async function findPath (paths: string | string[], options?: ResolvePathOptions, pathType: 'file' | 'dir'): Promise<string | null>
|
||||
|
||||
interface ResolvePathOptions {
|
||||
cwd?: string
|
||||
alias?: Record<string, string>
|
||||
extensions?: string[]
|
||||
}
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `paths`
|
||||
|
||||
**Type**: `string | string[]`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
A path or an array of paths to resolve.
|
||||
|
||||
#### `options`
|
||||
|
||||
**Type**: `ResolvePathOptions`
|
||||
|
||||
**Default**: `{}`
|
||||
|
||||
Options to pass to the resolver. This object can have the following properties:
|
||||
|
||||
- `cwd` (optional)
|
||||
|
||||
**Type**: `string`
|
||||
|
||||
**Default**: `process.cwd()`
|
||||
|
||||
Current working directory.
|
||||
|
||||
- `alias` (optional)
|
||||
|
||||
**Type**: `Record<string, string>`
|
||||
|
||||
**Default**: `{}`
|
||||
|
||||
Alias map.
|
||||
|
||||
- `extensions` (optional)
|
||||
|
||||
**Type**: `string[]`
|
||||
|
||||
**Default**: `['.js', '.mjs', '.ts', '.jsx', '.tsx', '.json']`
|
||||
|
||||
Extensions to try.
|
||||
|
||||
#### `pathType`
|
||||
|
||||
**Type**: `'file' | 'dir'`
|
||||
|
||||
**Default**: `'file'`
|
||||
|
||||
Type of path to resolve. If set to `'file'`, the function will try to resolve a file. If set to `'dir'`, the function will try to resolve a directory.
|
||||
|
||||
## `createResolver`
|
||||
|
||||
Creates resolver relative to base path.
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function createResolver (basePath: string | URL): Resolver
|
||||
|
||||
interface Resolver {
|
||||
resolve (...path: string[]): string
|
||||
resolvePath (path: string, options?: ResolvePathOptions): Promise<string>
|
||||
}
|
||||
|
||||
interface ResolvePathOptions {
|
||||
cwd?: string
|
||||
alias?: Record<string, string>
|
||||
extensions?: string[]
|
||||
}
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `basePath`
|
||||
|
||||
**Type**: `string`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
Base path to resolve from.
|
||||
|
||||
### Examples
|
||||
|
||||
```ts
|
||||
// https://github.com/vuejs/pinia/blob/v2/packages/nuxt
|
||||
import {
|
||||
defineNuxtModule,
|
||||
isNuxt2,
|
||||
createResolver,
|
||||
} from '@nuxt/kit'
|
||||
|
||||
export default defineNuxtModule({
|
||||
setup(options, nuxt) {
|
||||
const resolver = createResolver(import.meta.url)
|
||||
|
||||
nuxt.hook('modules:done', () => {
|
||||
if (isNuxt2()) {
|
||||
addPlugin(resolver.resolve('./runtime/plugin.vue2'))
|
||||
} else {
|
||||
addPlugin(resolver.resolve('./runtime/plugin.vue3'))
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
```
|
44
docs/3.api/4.kit/13.logging.md
Normal file
44
docs/3.api/4.kit/13.logging.md
Normal file
@ -0,0 +1,44 @@
|
||||
---
|
||||
title: "Logging"
|
||||
description: Nuxt Kit provides a set of utilities to help you work with logging. These functions allow you to log messages with extra features.
|
||||
---
|
||||
|
||||
# Logging
|
||||
|
||||
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/logger.ts)
|
||||
|
||||
Nuxt provides a logger instance that you can use to log messages with extra features. `useLogger` allows you to get a logger instance.
|
||||
|
||||
## `useLogger`
|
||||
|
||||
Returns a logger instance. It uses [consola](https://github.com/unjs/consola) under the hood.
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function useLogger (tag?: string): ConsolaInstance
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `tag`
|
||||
|
||||
**Type**: `string`
|
||||
|
||||
***Optional**: `true`
|
||||
|
||||
A tag to prefix all log messages with.
|
||||
|
||||
### Examples
|
||||
|
||||
```ts
|
||||
import { defineNuxtModule, useLogger } from '@nuxt/kit'
|
||||
|
||||
export default defineNuxtModule({
|
||||
setup(options, nuxt) {
|
||||
const logger = useLogger('my-module')
|
||||
|
||||
logger.info('Hello from my module!')
|
||||
}
|
||||
})
|
||||
```
|
490
docs/3.api/4.kit/14.builder.md
Normal file
490
docs/3.api/4.kit/14.builder.md
Normal file
@ -0,0 +1,490 @@
|
||||
---
|
||||
title: Builder
|
||||
description: Nuxt Kit provides a set of utilities to help you work with the builder. These functions allow you to extend the webpack and vite configurations.
|
||||
---
|
||||
|
||||
# Builder
|
||||
|
||||
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/build.ts)
|
||||
|
||||
Nuxt have builders based on [webpack](https://github.com/nuxt/nuxt/tree/main/packages/webpack) and [vite](https://github.com/nuxt/nuxt/tree/main/packages/vite). You can extend the config passed to each one using `extendWebpackConfig` and `extendViteConfig` functions. You can also add additional plugins via `addVitePlugin`, `addWebpackPlugin` and `addBuildPlugin`.
|
||||
|
||||
## `extendWebpackConfig`
|
||||
|
||||
Extends the webpack configuration. Callback function can be called multiple times, when applying to both client and server builds.
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function extendWebpackConfig (callback: ((config: WebpackConfig) => void), options?: ExtendWebpackConfigOptions): void
|
||||
|
||||
export interface ExtendWebpackConfigOptions {
|
||||
dev?: boolean
|
||||
build?: boolean
|
||||
server?: boolean
|
||||
client?: boolean
|
||||
prepend?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
::alert{type=info}
|
||||
See [webpack website](https://webpack.js.org/configuration/) for more information about webpack configuration.
|
||||
::
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `callback`
|
||||
|
||||
**Type**: `(config: WebpackConfig) => void`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
A callback function that will be called with the webpack configuration object.
|
||||
|
||||
#### `options`
|
||||
|
||||
**Type**: `ExtendWebpackConfigOptions`
|
||||
|
||||
**Default**: `{}`
|
||||
|
||||
Options to pass to the callback function. This object can have the following properties:
|
||||
|
||||
- `dev` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building in development mode.
|
||||
|
||||
- `build` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building in production mode.
|
||||
|
||||
- `server` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building the server bundle.
|
||||
|
||||
- `client` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building the client bundle.
|
||||
|
||||
- `prepend` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
If set to `true`, the callback function will be prepended to the array with `unshift()` instead of `push()`.
|
||||
|
||||
### Examples
|
||||
|
||||
```ts
|
||||
import { defineNuxtModule, extendWebpackConfig } from '@nuxt/kit'
|
||||
|
||||
export default defineNuxtModule({
|
||||
setup() {
|
||||
extendWebpackConfig((config) => {
|
||||
config.module?.rules.push({
|
||||
test: /\.txt$/,
|
||||
use: 'raw-loader'
|
||||
})
|
||||
})
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## `extendViteConfig`
|
||||
|
||||
Extends the Vite configuration. Callback function can be called multiple times, when applying to both client and server builds.
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function extendViteConfig (callback: ((config: ViteConfig) => void), options?: ExtendViteConfigOptions): void
|
||||
|
||||
export interface ExtendViteConfigOptions {
|
||||
dev?: boolean
|
||||
build?: boolean
|
||||
server?: boolean
|
||||
client?: boolean
|
||||
prepend?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
::alert{type=info}
|
||||
See [Vite website](https://vitejs.dev/config/) for more information about Vite configuration.
|
||||
::
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `callback`
|
||||
|
||||
**Type**: `(config: ViteConfig) => void`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
A callback function that will be called with the Vite configuration object.
|
||||
|
||||
#### `options`
|
||||
|
||||
**Type**: `ExtendViteConfigOptions`
|
||||
|
||||
**Default**: `{}`
|
||||
|
||||
Options to pass to the callback function. This object can have the following properties:
|
||||
|
||||
- `dev` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building in development mode.
|
||||
|
||||
- `build` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building in production mode.
|
||||
|
||||
- `server` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building the server bundle.
|
||||
|
||||
- `client` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building the client bundle.
|
||||
|
||||
- `prepend` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
If set to `true`, the callback function will be prepended to the array with `unshift()` instead of `push()`.
|
||||
|
||||
### Examples
|
||||
|
||||
```ts
|
||||
// https://github.com/Hrdtr/nuxt-appwrite
|
||||
import { defineNuxtModule, extendViteConfig } from '@nuxt/kit'
|
||||
|
||||
export default defineNuxtModule({
|
||||
setup() {
|
||||
extendViteConfig((config) => {
|
||||
config.optimizeDeps = config.optimizeDeps || {}
|
||||
config.optimizeDeps.include = config.optimizeDeps.include || []
|
||||
config.optimizeDeps.include.push('cross-fetch')
|
||||
})
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## `addWebpackPlugin`
|
||||
|
||||
Append webpack plugin to the config.
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function addWebpackPlugin (pluginOrGetter: PluginOrGetter, options?: ExtendWebpackConfigOptions): void
|
||||
|
||||
type PluginOrGetter = WebpackPluginInstance | WebpackPluginInstance[] | (() => WebpackPluginInstance | WebpackPluginInstance[])
|
||||
|
||||
interface ExtendWebpackConfigOptions {
|
||||
dev?: boolean
|
||||
build?: boolean
|
||||
server?: boolean
|
||||
client?: boolean
|
||||
prepend?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
::alert{type=info}
|
||||
See [webpack website](https://webpack.js.org/concepts/plugins/) for more information about webpack plugins. You can also use [this collection](https://webpack.js.org/awesome-webpack/#webpack-plugins) to find a plugin that suits your needs.
|
||||
::
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `pluginOrGetter`
|
||||
|
||||
**Type**: `PluginOrGetter`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
A webpack plugin instance or an array of webpack plugin instances. If a function is provided, it must return a webpack plugin instance or an array of webpack plugin instances.
|
||||
|
||||
#### `options`
|
||||
|
||||
**Type**: `ExtendWebpackConfigOptions`
|
||||
|
||||
**Default**: `{}`
|
||||
|
||||
Options to pass to the callback function. This object can have the following properties:
|
||||
|
||||
- `dev` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building in development mode.
|
||||
|
||||
- `build` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building in production mode.
|
||||
|
||||
- `server` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building the server bundle.
|
||||
|
||||
- `client` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building the client bundle.
|
||||
|
||||
- `prepend` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
If set to `true`, the callback function will be prepended to the array with `unshift()` instead of `push()`.
|
||||
|
||||
### Examples
|
||||
|
||||
```ts
|
||||
// https://github.com/nuxt-modules/eslint
|
||||
import EslintWebpackPlugin from 'eslint-webpack-plugin'
|
||||
import { defineNuxtModule, addWebpackPlugin } from '@nuxt/kit'
|
||||
|
||||
export default defineNuxtModule({
|
||||
meta: {
|
||||
name: 'nuxt-eslint',
|
||||
configKey: 'eslint',
|
||||
},
|
||||
defaults: nuxt => ({
|
||||
include: [`${nuxt.options.srcDir}/**/*.{js,jsx,ts,tsx,vue}`],
|
||||
lintOnStart: true,
|
||||
}),
|
||||
setup(options, nuxt) {
|
||||
const webpackOptions = {
|
||||
...options,
|
||||
context: nuxt.options.srcDir,
|
||||
files: options.include,
|
||||
lintDirtyModulesOnly: !options.lintOnStart
|
||||
}
|
||||
addWebpackPlugin(new EslintWebpackPlugin(webpackOptions), { server: false })
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## `addVitePlugin`
|
||||
|
||||
Append Vite plugin to the config.
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function addVitePlugin (pluginOrGetter: PluginOrGetter, options?: ExtendViteConfigOptions): void
|
||||
|
||||
type PluginOrGetter = VitePlugin | VitePlugin[] | (() => VitePlugin | VitePlugin[])
|
||||
|
||||
interface ExtendViteConfigOptions {
|
||||
dev?: boolean
|
||||
build?: boolean
|
||||
server?: boolean
|
||||
client?: boolean
|
||||
prepend?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
::alert{type=info}
|
||||
See [Vite website](https://vitejs.dev/guide/api-plugin.html) for more information about Vite plugins. You can also use [this repository](https://github.com/vitejs/awesome-vite#plugins) to find a plugin that suits your needs.
|
||||
::
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `pluginOrGetter`
|
||||
|
||||
**Type**: `PluginOrGetter`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
A Vite plugin instance or an array of Vite plugin instances. If a function is provided, it must return a Vite plugin instance or an array of Vite plugin instances.
|
||||
|
||||
#### `options`
|
||||
|
||||
**Type**: `ExtendViteConfigOptions`
|
||||
|
||||
**Default**: `{}`
|
||||
|
||||
Options to pass to the callback function. This object can have the following properties:
|
||||
|
||||
- `dev` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building in development mode.
|
||||
|
||||
- `build` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building in production mode.
|
||||
|
||||
- `server` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building the server bundle.
|
||||
|
||||
- `client` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building the client bundle.
|
||||
|
||||
- `prepend` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
If set to `true`, the callback function will be prepended to the array with `unshift()` instead of `push()`.
|
||||
|
||||
### Examples
|
||||
|
||||
```ts
|
||||
// https://github.com/yisibell/nuxt-svg-icons
|
||||
import { defineNuxtModule, addVitePlugin } from '@nuxt/kit'
|
||||
import { svg4VuePlugin } from 'vite-plugin-svg4vue'
|
||||
|
||||
export default defineNuxtModule({
|
||||
meta: {
|
||||
name: 'nuxt-svg-icons',
|
||||
configKey: 'nuxtSvgIcons',
|
||||
},
|
||||
defaults: {
|
||||
svg4vue: {
|
||||
assetsDirName: 'assets/icons',
|
||||
},
|
||||
},
|
||||
setup(options) {
|
||||
addVitePlugin(svg4VuePlugin(options.svg4vue))
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## `addBuildPlugin`
|
||||
|
||||
Builder-agnostic version of `addWebpackPlugin` and `addVitePlugin`. It will add the plugin to both webpack and vite configurations if they are present.
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function addBuildPlugin (pluginFactory: AddBuildPluginFactory, options?: ExtendConfigOptions): void
|
||||
|
||||
interface AddBuildPluginFactory {
|
||||
vite?: () => VitePlugin | VitePlugin[]
|
||||
webpack?: () => WebpackPluginInstance | WebpackPluginInstance[]
|
||||
}
|
||||
|
||||
interface ExtendConfigOptions {
|
||||
dev?: boolean
|
||||
build?: boolean
|
||||
server?: boolean
|
||||
client?: boolean
|
||||
prepend?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `pluginFactory`
|
||||
|
||||
**Type**: `AddBuildPluginFactory`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
A factory function that returns an object with `vite` and/or `webpack` properties. These properties must be functions that return a Vite plugin instance or an array of Vite plugin instances and/or a webpack plugin instance or an array of webpack plugin instances.
|
||||
|
||||
#### `options`
|
||||
|
||||
**Type**: `ExtendConfigOptions`
|
||||
|
||||
**Default**: `{}`
|
||||
|
||||
Options to pass to the callback function. This object can have the following properties:
|
||||
|
||||
- `dev` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building in development mode.
|
||||
|
||||
- `build` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building in production mode.
|
||||
|
||||
- `server` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building the server bundle.
|
||||
|
||||
- `client` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
If set to `true`, the callback function will be called when building the client bundle.
|
||||
|
||||
- `prepend` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
If set to `true`, the callback function will be prepended to the array with `unshift()` instead of `push()`.
|
43
docs/3.api/4.kit/15.examples.md
Normal file
43
docs/3.api/4.kit/15.examples.md
Normal file
@ -0,0 +1,43 @@
|
||||
---
|
||||
title: "Examples"
|
||||
description: Examples of Nuxt Kit utilities in use.
|
||||
---
|
||||
|
||||
# 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/storybook-nuxt/blob/main/packages/storybook-nuxt/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)
|
||||
```
|
146
docs/3.api/4.kit/2.programmatic.md
Normal file
146
docs/3.api/4.kit/2.programmatic.md
Normal file
@ -0,0 +1,146 @@
|
||||
---
|
||||
title: "Programmatic Usage"
|
||||
description: Nuxt Kit provides a set of utilities to help you work with Nuxt programmatically. These functions allow you to load Nuxt, build Nuxt, and load Nuxt configuration.
|
||||
---
|
||||
|
||||
# Programmatic Usage
|
||||
|
||||
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/loader)
|
||||
|
||||
Programmatic usage can be helpful 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 (options: LoadNuxtConfigOptions): Promise<NuxtOptions>
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `options`
|
||||
|
||||
**Type**: `LoadNuxtConfigOptions`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
Options to pass in [`c12`](https://github.com/unjs/c12#options) `loadConfig` call.
|
||||
|
||||
## `writeTypes`
|
||||
|
||||
Generates tsconfig.json and writes it to the project buildDir.
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function writeTypes (nuxt?: Nuxt): void
|
||||
|
||||
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>
|
||||
}
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `nuxt`
|
||||
|
||||
**Type**: `Nuxt`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
Nuxt instance to build. It can be retrieved from the context via `useNuxt()` call.
|
223
docs/3.api/4.kit/3.compatibility.md
Normal file
223
docs/3.api/4.kit/3.compatibility.md
Normal file
@ -0,0 +1,223 @@
|
||||
---
|
||||
title: "Compatibility"
|
||||
description: Nuxt Kit provides a set of utilities to help you check the compatibility of your modules with different Nuxt versions.
|
||||
---
|
||||
|
||||
# Compatibility
|
||||
|
||||
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/compatibility.ts)
|
||||
|
||||
Nuxt Kit utilities can be used in Nuxt 3, Nuxt 2 with Bridge and even 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.
|
||||
|
||||
## `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.
|
322
docs/3.api/4.kit/4.autoimports.md
Normal file
322
docs/3.api/4.kit/4.autoimports.md
Normal file
@ -0,0 +1,322 @@
|
||||
---
|
||||
title: "Auto-imports"
|
||||
description: Nuxt Kit provides a set of utilities to help you work with auto-imports. These functions allow you to register your own utils, composables and Vue APIs.
|
||||
---
|
||||
|
||||
# Auto-imports
|
||||
|
||||
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/imports.ts)
|
||||
|
||||
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. With Nuxt Kit you can also add your own auto-imports. `addImports` and `addImportsDir` allow you to add imports to the Nuxt application. `addImportsSources` allows you to add listed imports from 3rd party packages to the Nuxt application.
|
||||
|
||||
::alert{type=info}
|
||||
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](/docs/api/kit/pages), [Components](/docs/api/kit/components), [Plugins](/docs/api/kit/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.
|
||||
|
||||
## `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[], options?: { prepend?: boolean }): void
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `dirs`
|
||||
|
||||
**Type**: `string | string[]`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
A string or an array of strings with the path to the directory to import from.
|
||||
|
||||
#### `options`
|
||||
|
||||
**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({
|
||||
meta: {
|
||||
name: '@vueuse/motion',
|
||||
configKey: 'motion',
|
||||
},
|
||||
setup(options, nuxt) {
|
||||
const resolver = createResolver(import.meta.url)
|
||||
addImportsDir(resolver.resolve('./runtime/composables'))
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## `addImportsSources`
|
||||
|
||||
Add listed imports to the Nuxt application.
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function addImportsSources (importSources: ImportSource | ImportSource[]): 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
|
||||
}
|
||||
|
||||
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<keyof typeof import('h3')>,
|
||||
})
|
||||
}
|
||||
})
|
||||
```
|
284
docs/3.api/4.kit/5.components.md
Normal file
284
docs/3.api/4.kit/5.components.md
Normal file
@ -0,0 +1,284 @@
|
||||
---
|
||||
title: "Components"
|
||||
description: Nuxt Kit provides a set of utilities to help you work with components. You can register components globally or locally, and also add directories to be scanned for components.
|
||||
---
|
||||
|
||||
# Components
|
||||
|
||||
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/components.ts)
|
||||
|
||||
Components are the building blocks of your Nuxt application. They are reusable Vue instances that can be used to create a user interface. 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.
|
||||
|
||||
## `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 (options: 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
|
||||
|
||||
#### `options`
|
||||
|
||||
**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(options.name)`
|
||||
|
||||
Pascal case component name. If not provided, it will be generated from the component name.
|
||||
|
||||
- `kebabName` (optional)
|
||||
|
||||
**Type**: `kebabCase(options.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(options.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.
|
129
docs/3.api/4.kit/6.context.md
Normal file
129
docs/3.api/4.kit/6.context.md
Normal file
@ -0,0 +1,129 @@
|
||||
---
|
||||
title: "Context"
|
||||
description: Nuxt Kit provides a set of utilities to help you work with context.
|
||||
---
|
||||
|
||||
# Context
|
||||
|
||||
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/context.ts)
|
||||
|
||||
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.
|
||||
|
||||
::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()`. 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
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
::
|
267
docs/3.api/4.kit/7.pages.md
Normal file
267
docs/3.api/4.kit/7.pages.md
Normal file
@ -0,0 +1,267 @@
|
||||
---
|
||||
title: Pages
|
||||
description: Nuxt Kit provides a set of utilities to help you create and use pages. You can use these utilities to manipulate the pages configuration or to define route rules.
|
||||
---
|
||||
|
||||
# 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`
|
||||
|
||||
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 useful 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).
|
||||
::
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function extendRouteRules (route: string, rule: NitroRouteConfig, options: ExtendRouteRulesOptions): void
|
||||
|
||||
interface NitroRouteConfig {
|
||||
cache?: CacheOptions | false;
|
||||
headers?: Record<string, string>;
|
||||
redirect?: string | { to: string; statusCode?: HTTPStatusCode };
|
||||
prerender?: boolean;
|
||||
proxy?: string | ({ to: string } & ProxyOptions);
|
||||
isr?: number | boolean;
|
||||
cors?: boolean;
|
||||
swr?: boolean | number;
|
||||
static?: boolean | number;
|
||||
}
|
||||
|
||||
interface ExtendRouteRulesOptions {
|
||||
override?: boolean
|
||||
}
|
||||
|
||||
interface CacheOptions {
|
||||
swr?: boolean
|
||||
name?: string
|
||||
group?: string
|
||||
integrity?: any
|
||||
maxAge?: number
|
||||
staleMaxAge?: number
|
||||
base?: string
|
||||
headersOnly?: boolean
|
||||
}
|
||||
|
||||
// See https://www.jsdocs.io/package/h3#ProxyOptions
|
||||
interface ProxyOptions {
|
||||
headers?: RequestHeaders | HeadersInit;
|
||||
fetchOptions?: RequestInit & { duplex?: Duplex } & {
|
||||
ignoreResponseError?: boolean;
|
||||
};
|
||||
fetch?: typeof fetch;
|
||||
sendStream?: boolean;
|
||||
streamRequest?: boolean;
|
||||
cookieDomainRewrite?: string | Record<string, string>;
|
||||
cookiePathRewrite?: string | Record<string, string>;
|
||||
onResponse?: (event: H3Event, response: Response) => void;
|
||||
}
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `route`
|
||||
|
||||
**Type**: `string`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
A route pattern to match against.
|
||||
|
||||
#### `rule`
|
||||
|
||||
**Type**: `NitroRouteConfig`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
A route configuration to apply to the matched route.
|
||||
|
||||
#### `options`
|
||||
|
||||
**Type**: `ExtendRouteRulesOptions`
|
||||
|
||||
**Default**: `{}`
|
||||
|
||||
Options to pass to the route configuration. If `override` is set to `true`, it will override the existing route configuration.
|
||||
|
||||
### Examples
|
||||
|
||||
```ts
|
||||
// https://github.com/directus/website/blob/main/modules/redirects.ts
|
||||
import { createResolver, defineNuxtModule, extendRouteRules, extendPages } from '@nuxt/kit'
|
||||
|
||||
export default defineNuxtModule({
|
||||
setup(options) {
|
||||
const resolver = createResolver(import.meta.url)
|
||||
|
||||
extendPages((pages) => {
|
||||
pages.unshift({
|
||||
name: 'preview-new',
|
||||
path: '/preview-new',
|
||||
file: resolver.resolve('runtime/preview.vue')
|
||||
})
|
||||
})
|
||||
|
||||
extendRouteRules('/preview', {
|
||||
redirect: {
|
||||
to: '/preview-new',
|
||||
statusCode: 302
|
||||
}
|
||||
})
|
||||
|
||||
extendRouteRules('/preview-new', {
|
||||
cache: {
|
||||
maxAge: 60 * 60 * 24 * 7
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## `addRouteMiddleware`
|
||||
|
||||
Registers route middlewares to be available for all routes or for specific routes.
|
||||
|
||||
Route middlewares can be also defined in plugins via [`addRouteMiddleware`](/docs/api/utils/add-route-middleware) composable.
|
||||
|
||||
::alert{type=info icon=👉}
|
||||
Read more about route middlewares in the [Route middleware documentation](/docs/getting-started/routing#route-middleware).
|
||||
::
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function addRouteMiddleware (input: NuxtMiddleware | NuxtMiddleware[], options: AddRouteMiddlewareOptions): void
|
||||
|
||||
type NuxtMiddleware = {
|
||||
name: string
|
||||
path: string
|
||||
global?: boolean
|
||||
}
|
||||
|
||||
interface AddRouteMiddlewareOptions {
|
||||
override?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `input`
|
||||
|
||||
**Type**: `NuxtMiddleware | NuxtMiddleware[]`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
A middleware object or an array of middleware objects with the following properties:
|
||||
|
||||
- `name` (required)
|
||||
|
||||
**Type**: `string`
|
||||
|
||||
Middleware name.
|
||||
|
||||
- `path` (required)
|
||||
|
||||
**Type**: `string`
|
||||
|
||||
Path to the middleware.
|
||||
|
||||
- `global` (optional)
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
If enabled, registers middleware to be available for all routes.
|
||||
|
||||
#### `options`
|
||||
|
||||
**Type**: `AddRouteMiddlewareOptions`
|
||||
|
||||
**Default**: `{}`
|
||||
|
||||
Options to pass to the middleware. If `override` is set to `true`, it will override the existing middleware with the same name.
|
||||
|
||||
### Examples
|
||||
|
||||
::code-group
|
||||
|
||||
```ts [runtime/auth.ts]
|
||||
export default defineNuxtRouteMiddleware((to, from) => {
|
||||
// isAuthenticated() is an example method verifying if a user is authenticated
|
||||
if (to.path !== '/login' && isAuthenticated() === false) {
|
||||
return navigateTo('/login')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
```ts
|
||||
import { createResolver, defineNuxtModule, addRouteMiddleware } from '@nuxt/kit'
|
||||
|
||||
export default defineNuxtModule({
|
||||
setup() {
|
||||
const resolver = createResolver(import.meta.url)
|
||||
|
||||
addRouteMiddleware({
|
||||
name: 'auth',
|
||||
path: resolver.resolve('runtime/auth.ts'),
|
||||
global: true
|
||||
})
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
::
|
79
docs/3.api/4.kit/8.layout.md
Normal file
79
docs/3.api/4.kit/8.layout.md
Normal file
@ -0,0 +1,79 @@
|
||||
---
|
||||
title: "Layout"
|
||||
description: "Nuxt Kit provides a set of utilities to help you work with layouts."
|
||||
---
|
||||
|
||||
# Layout
|
||||
|
||||
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/layout.ts)
|
||||
|
||||
Layouts is used to be a wrapper around your pages. It can be used to wrap your pages with common components, for example, a header and a footer. Layouts can be registered using `addLayout` utility.
|
||||
|
||||
## `addLayout`
|
||||
|
||||
Register template as layout and add it to the layouts.
|
||||
|
||||
::alert{type=info icon=👉}
|
||||
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.
|
||||
::
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
function addLayout (layout: NuxtTemplate | string, name: string): void
|
||||
|
||||
interface NuxtTemplate {
|
||||
src?: string
|
||||
filename?: string
|
||||
dst?: string
|
||||
options?: Record<string, any>
|
||||
getContents?: (data: Record<string, any>) => string | Promise<string>
|
||||
write?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `layout`
|
||||
|
||||
**Type**: `NuxtTemplate | string`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
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.
|
||||
|
||||
- `options` (optional)
|
||||
|
||||
**Type**: `Options`
|
||||
|
||||
Options to pass to the template.
|
||||
|
||||
- `getContents` (optional)
|
||||
|
||||
**Type**: `(data: Options) => string | Promise<string>`
|
||||
|
||||
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.
|
253
docs/3.api/4.kit/9.plugins.md
Normal file
253
docs/3.api/4.kit/9.plugins.md
Normal file
@ -0,0 +1,253 @@
|
||||
---
|
||||
title: Plugins
|
||||
description: Nuxt Kit provides a set of utilities to help you create and use plugins. You can add plugins or plugin templates to your module using these functions.
|
||||
---
|
||||
|
||||
# Plugins
|
||||
|
||||
[source code](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/plugin.ts)
|
||||
|
||||
Plugins are self-contained code that usually add app-level functionality to Vue. In Nuxt, plugins are automatically imported from the `plugins` directory. However, if you need to ship a plugin with your module, Nuxt Kit provides the `addPlugin` and `addPluginTemplate` methods. These utils allow you to customize the plugin configuration to better suit your needs.
|
||||
|
||||
## `addPlugin`
|
||||
|
||||
Registers a Nuxt plugin and to the plugins array.
|
||||
|
||||
### Type
|
||||
|
||||
```ts
|
||||
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
|
||||
|
||||
interface NuxtPluginTemplate<Options = Record<string, any>> {
|
||||
src?: string,
|
||||
filename?: string,
|
||||
dst?: string,
|
||||
mode?: 'all' | 'server' | 'client',
|
||||
options?: Options,
|
||||
getContents?: (data: Options) => string | Promise<string>,
|
||||
write?: boolean,
|
||||
order?: number
|
||||
}
|
||||
|
||||
interface AddPluginOptions { append?: boolean }
|
||||
|
||||
interface NuxtPlugin {
|
||||
src: string
|
||||
mode?: 'all' | 'server' | 'client'
|
||||
order?: number
|
||||
}
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
#### `pluginOptions`
|
||||
|
||||
**Type**: `NuxtPluginTemplate`
|
||||
|
||||
**Required**: `true`
|
||||
|
||||
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.
|
||||
|
||||
- `options` (optional)
|
||||
|
||||
**Type**: `Options`
|
||||
|
||||
Options to pass to the template.
|
||||
|
||||
- `getContents` (optional)
|
||||
|
||||
**Type**: `(data: Options) => string | Promise<string>`
|
||||
|
||||
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.
|
||||
|
||||
- `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'
|
||||
import { defineNuxtPlugin } from '#app'
|
||||
|
||||
export default defineNuxtPlugin((nuxtApp) => {
|
||||
const firebaseApp = nuxtApp.$firebaseApp
|
||||
|
||||
nuxtApp.vueApp.use(VueFire, { firebaseApp })
|
||||
|
||||
<% if(options.ssr) { %>
|
||||
if (process.server) {
|
||||
nuxtApp.payload.vuefire = useSSRInitialState(undefined, firebaseApp)
|
||||
} else if (nuxtApp.payload?.vuefire) {
|
||||
useSSRInitialState(nuxtApp.payload.vuefire, firebaseApp)
|
||||
}
|
||||
<% } %>
|
||||
})
|
||||
```
|
||||
|
||||
::
|
3
docs/3.api/4.kit/_dir.yml
Normal file
3
docs/3.api/4.kit/_dir.yml
Normal file
@ -0,0 +1,3 @@
|
||||
title: Kit Utilities
|
||||
navigation.icon: uil:suitcase-alt
|
||||
image: '/socials/advanced.jpg'
|
Loading…
Reference in New Issue
Block a user