Шаблоны

Исходники
Nuxt Kit предоставляет набор утилит, которые помогают вам работать с шаблонами. Эти функции позволяют вам генерировать дополнительные файлы во время разработки и сборки.

Шаблоны позволяют генерировать дополнительные файлы во время разработки и сборки. Эти файлы будут доступны в виртуальной файловой системе и могут быть использованы в плагинах, лейаутах, компонентах и т.д. addTemplate и addTypeTemplate позволяют вам добавлять шаблоны в приложение Nuxt. updateTemplates позволяет вам повторно генерировать шаблоны, соответствующие фильтру.

addTemplate

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

Usage

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' })
    })
  }
})

Тип

// @errors: 2391
import type { NuxtTemplate, ResolvedNuxtTemplate } from '@nuxt/schema'
// ---cut---
function addTemplate (template: NuxtTemplate | string): ResolvedNuxtTemplate

Параметры

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 must have the following properties:

PropertyTypeRequiredDescription
srcstringfalsePath to the template. If src is not provided, getContents must be provided instead.
filenamestringfalseFilename of the template. If filename is not provided, it will be generated from the src path. In this case, the src option is required.
dststringfalsePath to the destination file. If dst is not provided, it will be generated from the filename path and nuxt buildDir option.
optionsOptionsfalseOptions to pass to the template.
getContents(data: Options) => string | Promise<string>falseA 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.
writebooleanfalseIf set to true, the template will be written to the destination file. Otherwise, the template will be used only in virtual filesystem.

Примеры

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.

module.ts
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 module above, we generate a virtual file named meta.config.mjs. In the runtime plugin, we can import it using the #build alias:

runtime/plugin.ts
import { createHead as createServerHead } from '@unhead/vue/server'
import { createHead as createClientHead } from '@unhead/vue/client'
import { defineNuxtPlugin } from '#imports'
// @ts-ignore
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

Отображает заданный шаблон во время сборки в buildDir проекта, а затем регистрирует его в качестве типов.

Usage

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
}`,
    })
  },
})

Тип

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. If a template object is provided, it must have the following properties:

PropertyTypeRequiredDescription
srcstringfalsePath to the template. If src is not provided, getContents must be provided instead.
filenamestringfalseFilename of the template. If filename is not provided, it will be generated from the src path. In this case, the src option is required.
dststringfalsePath to the destination file. If dst is not provided, it will be generated from the filename path and nuxt buildDir option.
optionsOptionsfalseOptions to pass to the template.
getContents(data: Options) => string | Promise<string>falseA 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.

context: An optional context object can be passed to control where the type is added. If omitted, the type will only be added to the Nuxt context. This object supports the following properties:

PropertyTypeRequiredDescription
nuxtbooleanfalseIf set to true, the type will be added to the Nuxt context.
nitrobooleanfalseIf set to true, the type will be added to the Nitro context.

Examples

Adding Type Templates to the Nitro Context

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

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,
    })
  },
})

This allows the #auth-utils module to be used within the Nitro context.

server/api/auth.ts
import type { User } from '#auth-utils'

export default eventHandler(() => {
  const user: User = {
    id: '123',
    name: 'John Doe',
  }

  // do something with the user

  return user
})

addServerTemplate

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

Usage

import { addServerTemplate, defineNuxtModule } from '@nuxt/kit'

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

Type

// @errors: 2391
import type { NuxtServerTemplate } from '@nuxt/schema'
// ---cut---
function addServerTemplate (template: NuxtServerTemplate): NuxtServerTemplate

Параметры

template: A template object. It must have the following properties:

PropertyTypeRequiredDescription
filenamestringtrueFilename of the template.
getContents() => string | Promise<string>trueA function that will be called with the options object. It should return a string or a promise that resolves to a string.

Examples

Creating a Virtual File for Nitro

In this example, we create a virtual file that can be used within the Nuxt Nitro server build.

import { addServerTemplate, defineNuxtModule } from '@nuxt/kit'

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

And then in a runtime file

server/api/test.ts
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.

Usage

import { defineNuxtModule, updateTemplates } from '@nuxt/kit'
import { resolve } from 'pathe'

export default defineNuxtModule({
  setup (options, nuxt) {
    const updateTemplatePaths = [
      resolve(nuxt.options.srcDir, 'pages'),
    ]
    // следить и перестраивать список шаблонов маршрутов, когда одна из страниц изменяется
    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',
        })
      }
    })
  },
})

Type

async function updateTemplates (options: UpdateTemplatesOptions): void

Parameters

options: Options to pass to the template. This object can have the following property:

PropertyTypeRequiredDescription
filter(template: ResolvedNuxtTemplate) => booleanfalseA 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.