Nuxt/docs/3.api/5.kit/10.templates.md

283 lines
7.3 KiB
Markdown

---
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.
links:
- label: Source
icon: i-simple-icons-github
to: https://github.com/nuxt/nuxt/blob/main/packages/kit/src/template.ts
size: xs
---
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 '#imports'
// @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'
})
}
})
}
})
```