perf(nuxt): set pages on nuxt app and deduplicate calls (#24032)

This commit is contained in:
Daniel Roe 2023-10-31 01:55:40 +09:00 committed by GitHub
parent 802cf7a1e9
commit 2011e6c159
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 12 deletions

View File

@ -53,6 +53,11 @@ export default defineNuxtModule({
}
nuxt.options.pages = await isPagesEnabled()
nuxt.hook('app:templates', async (app) => {
app.pages = await resolvePagesRoutes()
await nuxt.callHook('pages:extend', app.pages)
})
// Restart Nuxt when pages dir is added or removed
const restartPaths = nuxt.options._layers.flatMap((layer) => {
const pagesDir = (layer.config.rootDir === nuxt.options.rootDir ? nuxt.options : layer.config).dir?.pages || 'pages'
@ -110,8 +115,11 @@ export default defineNuxtModule({
logs: nuxt.options.debug,
async beforeWriteFiles (rootPage) {
rootPage.children.forEach(child => child.delete())
const pages = await resolvePagesRoutes()
await nuxt.callHook('pages:extend', pages)
let pages = nuxt.apps.default?.pages
if (!pages) {
pages = await resolvePagesRoutes()
await nuxt.callHook('pages:extend', pages)
}
function addPage (parent: EditableTreeNode, page: NuxtPage) {
// @ts-expect-error TODO: either fix types upstream or figure out another
// way to add a route without a file, which must be possible
@ -339,12 +347,9 @@ export default defineNuxtModule({
)
// Do not prefetch page chunks
nuxt.hook('build:manifest', async (manifest) => {
nuxt.hook('build:manifest', (manifest) => {
if (nuxt.options.dev) { return }
const pages = await resolvePagesRoutes()
await nuxt.callHook('pages:extend', pages)
const sourceFiles = getSources(pages)
const sourceFiles = getSources(nuxt.apps.default.pages || [])
for (const key in manifest) {
if (manifest[key].isEntry) {
@ -357,10 +362,8 @@ export default defineNuxtModule({
// Add routes template
addTemplate({
filename: 'routes.mjs',
async getContents () {
const pages = await resolvePagesRoutes()
await nuxt.callHook('pages:extend', pages)
const { routes, imports } = normalizeRoutes(pages)
getContents ({ app }) {
const { routes, imports } = normalizeRoutes(app.pages)
return [...imports, `export default ${routes}`].join('\n')
}
})

View File

@ -1,6 +1,6 @@
import type { Hookable } from 'hookable'
import type { Ignore } from 'ignore'
import type { NuxtHooks, NuxtLayout, NuxtMiddleware } from './hooks'
import type { NuxtHooks, NuxtLayout, NuxtMiddleware, NuxtPage } from './hooks'
import type { Component } from './components'
import type { NuxtOptions } from './config'
@ -61,6 +61,7 @@ export interface NuxtApp {
middleware: NuxtMiddleware[]
templates: NuxtTemplate[]
configs: string[]
pages?: NuxtPage[]
}
export interface Nuxt {