feat(kit): add addLayout (#5537)

This commit is contained in:
Daniel Roe 2022-06-27 12:47:54 +01:00 committed by GitHub
parent d2c3727c5f
commit 6f8b7a9043
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 47 additions and 14 deletions

View File

@ -14,6 +14,7 @@ export * from './compatibility'
export * from './components'
export * from './context'
export * from './ignore'
export * from './layout'
export * from './pages'
export * from './plugin'
export * from './resolve'

View File

@ -0,0 +1,42 @@
import type { NuxtTemplate } from '@nuxt/schema'
import { join, parse, relative } from 'pathe'
import { kebabCase } from 'scule'
import { isNuxt2 } from './compatibility'
import { useNuxt } from './context'
import { logger } from './logger'
import { addTemplate } from './template'
export function addLayout (tmpl: NuxtTemplate, name?: string) {
const nuxt = useNuxt()
const { filename, src } = addTemplate(tmpl)
const layoutName = kebabCase(name || parse(tmpl.filename).name).replace(/["']/g, '')
if (isNuxt2(nuxt)) {
// Nuxt 2 adds layouts in options
const layout = nuxt.options.layouts[layoutName]
if (layout) {
return logger.warn(
`Not overriding \`${layoutName}\` (provided by \`${layout}\`) with \`${src || filename}\`.`
)
}
nuxt.options.layouts[layoutName] = `./${filename}`
if (name === 'error') {
this.addErrorLayout(filename)
}
return
}
// Nuxt 3 adds layouts on app
nuxt.hook('app:templates', (app) => {
if (layoutName in app.layouts) {
const relativePath = relative(nuxt.options.srcDir, app.layouts[layoutName].file)
return logger.warn(
`Not overriding \`${layoutName}\` (provided by \`~/${relativePath}\`) with \`${src || filename}\`.`
)
}
app.layouts[layoutName] = {
file: join('#build', filename),
name: layoutName
}
})
}

View File

@ -1,8 +1,8 @@
import { parse, relative } from 'pathe'
import { relative } from 'pathe'
import type { Nuxt, NuxtPluginTemplate, NuxtTemplate, ModuleContainer } from '@nuxt/schema'
import { logger } from '../logger'
import { chainFn } from '../internal/task'
import { addTemplate } from '../template'
import { addLayout } from '../layout'
import { addServerMiddleware } from '../server'
import { isNuxt2 } from '../compatibility'
import { addPluginTemplate } from '../plugin'
@ -61,18 +61,8 @@ export function useModuleContainer (nuxt: Nuxt = useNuxt()): ModuleContainer {
return addPluginTemplate(pluginTemplate)
},
addLayout (tmpl: NuxtTemplate, name: string) {
const { filename, src } = addTemplate(tmpl)
const layoutName = name || parse(src).name
const layout = nuxt.options.layouts[layoutName]
if (layout) {
logger.warn(`Duplicate layout registration, "${layoutName}" has been registered as "${layout}"`)
}
nuxt.options.layouts[layoutName] = `./${filename}`
if (name === 'error') {
this.addErrorLayout(filename)
}
addLayout (tmpl: NuxtTemplate, name?: string) {
return addLayout(tmpl, name)
},
addErrorLayout (dst: string) {