> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/nuxt/nuxt/llms.txt
> Use this file to discover all available pages before exploring further.

# Templates

> Template utilities to generate extra files during development and build time

# Templates

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 allow you 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`

Renders given template during build into the virtual file system, and optionally to disk in the project `buildDir`.

### Type

```ts theme={null}
function addTemplate(template: NuxtTemplate | string): ResolvedNuxtTemplate
```

### Parameters

**`template`**: 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 can have the following properties:

| Property      | Type                                           | Required | Description                                                                                                |
| ------------- | ---------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------- |
| `src`         | `string`                                       | `false`  | Path to the template. If `src` is not provided, `getContents` must be provided instead.                    |
| `filename`    | `string`                                       | `false`  | Filename of the template. If not provided, generated from the `src` path. In this case, `src` is required. |
| `dst`         | `string`                                       | `false`  | Path to the destination file. If not provided, generated from the `filename` path and nuxt `buildDir`.     |
| `options`     | `Options`                                      | `false`  | Options to pass to the template.                                                                           |
| `getContents` | `(data: Options) => string \| Promise<string>` | `false`  | A function that returns template contents. If `src` is provided, this is ignored.                          |
| `write`       | `boolean`                                      | `false`  | If set to `true`, the template will be written to disk. Otherwise, used only in virtual filesystem.        |

### Usage

```ts theme={null}
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' }),
    })
  },
})
```

## Creating a Virtual File for Runtime Plugin

In this example, we merge an object inside a module and consume the result in a runtime plugin.

```ts theme={null}
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' }),
    })
  },
})
```

In the runtime plugin, we can import it using the `#build` alias:

```ts theme={null}
import { createHead as createServerHead } from '@unhead/vue/server'
import { createHead as createClientHead } from '@unhead/vue/client'
import { defineNuxtPlugin } from '#imports'
// @ts-expect-error - virtual file
import metaConfig from '#build/meta.config.mjs'

export default defineNuxtPlugin((nuxtApp) => {
  const createHead = import.meta.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 theme={null}
function addTypeTemplate(
  template: NuxtTypeTemplate | string,
  context?: { nitro?: boolean, nuxt?: boolean }
): ResolvedNuxtTemplate
```

### Parameters

**`template`**: 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. Properties are the same as `addTemplate`.

**`context`**: Optional context object:

| Property | Type      | Required | Description                                                    |
| -------- | --------- | -------- | -------------------------------------------------------------- |
| `nuxt`   | `boolean` | `false`  | If set to `true`, the type will be added to the Nuxt context.  |
| `nitro`  | `boolean` | `false`  | If set to `true`, the type will be added to the Nitro context. |

### Usage

```ts theme={null}
import { addTypeTemplate, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  setup() {
    addTypeTemplate({
      filename: 'types/markdown.d.ts',
      getContents: () => `
declare module '*.md' {
  import type { ComponentOptions } from 'vue'
  const Component: ComponentOptions
  export default Component
}
      `,
    })
  },
})
```

## Adding Type Templates to the Nitro Context

By default, `addTypeTemplate` only adds the type declarations to the Nuxt context. To also add them to the Nitro context, set `nitro` to true.

```ts theme={null}
import { addTypeTemplate, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  setup() {
    addTypeTemplate({
      filename: 'types/auth.d.ts',
      getContents: () => `
declare module '#auth-utils' {
  interface User {
    id: string;
    name: string;
  }
}
      `,
    }, {
      nitro: true,
    })
  },
})
```

## `addServerTemplate`

Adds a virtual file that can be used within the Nuxt Nitro server build.

### Type

```ts theme={null}
function addServerTemplate(template: NuxtServerTemplate): NuxtServerTemplate
```

### Parameters

**`template`**: A template object with the following properties:

| Property      | Type                              | Required | Description                                    |
| ------------- | --------------------------------- | -------- | ---------------------------------------------- |
| `filename`    | `string`                          | `true`   | Filename of the template.                      |
| `getContents` | `() => string \| Promise<string>` | `true`   | A function that returns the template contents. |

### Usage

```ts theme={null}
import { addServerTemplate, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  setup() {
    addServerTemplate({
      filename: '#my-module/test.mjs',
      getContents() {
        return 'export const test = 123'
      },
    })
  },
})
```

Then in a runtime file:

```ts theme={null}
import { test } from '#my-module/test.js'

export default eventHandler(() => {
  return test
})
```

## `updateTemplates`

Regenerate templates that match the filter. If no filter is provided, all templates will be regenerated.

### Type

```ts theme={null}
async function updateTemplates(options: UpdateTemplatesOptions): void
```

### Parameters

**`options`**: Options object:

| Property | Type                                          | Required | Description                                                                                                             |
| -------- | --------------------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------- |
| `filter` | `(template: ResolvedNuxtTemplate) => boolean` | `false`  | A function that returns whether the template should be regenerated. If not provided, all templates will be regenerated. |

### Usage

```ts theme={null}
import { defineNuxtModule, updateTemplates } from '@nuxt/kit'
import { resolve } from 'pathe'

export default defineNuxtModule({
  setup(options, nuxt) {
    const updateTemplatePaths = [
      resolve(nuxt.options.srcDir, 'pages'),
    ]
    
    // 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',
        })
      }
    })
  },
})
```

## Source

[View source on GitHub](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/template.ts)
