From ec9dcdb093877cb46b257da66f6bcd1dc990290d Mon Sep 17 00:00:00 2001 From: Dario Ferderber Date: Mon, 15 May 2023 14:47:30 +0200 Subject: [PATCH] fix(nuxt): allow `pages:extend` to enable pages module (#20806) --- docs/2.guide/3.going-further/3.modules.md | 4 ++-- packages/nuxt/src/pages/module.ts | 13 +++++++++---- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/docs/2.guide/3.going-further/3.modules.md b/docs/2.guide/3.going-further/3.modules.md index ba73c55f56..a6cfbf7625 100644 --- a/docs/2.guide/3.going-further/3.modules.md +++ b/docs/2.guide/3.going-further/3.modules.md @@ -414,8 +414,8 @@ export default defineNuxtModule({ } }, setup (options, nuxt) { - // Programmatically hook to the `page:extend` hook - nuxt.hook('page:extend', (pages) => { + // Programmatically hook to the `pages:extend` hook + nuxt.hook('pages:extend', (pages) => { console.info(`Discovered ${pages.length} pages`); }) } diff --git a/packages/nuxt/src/pages/module.ts b/packages/nuxt/src/pages/module.ts index bfd569ce3e..46bbdab5ec 100644 --- a/packages/nuxt/src/pages/module.ts +++ b/packages/nuxt/src/pages/module.ts @@ -29,7 +29,7 @@ export default defineNuxtModule({ // Disable module (and use universal router) if pages dir do not exists or user has disabled it const isNonEmptyDir = (dir: string) => existsSync(dir) && readdirSync(dir).length const userPreference = nuxt.options.pages - const isPagesEnabled = () => { + const isPagesEnabled = async () => { if (typeof userPreference === 'boolean') { return userPreference } @@ -39,19 +39,24 @@ export default defineNuxtModule({ if (pagesDirs.some(dir => isNonEmptyDir(dir))) { return true } + + const pages = await resolvePagesRoutes() + await nuxt.callHook('pages:extend', pages) + if (pages.length) { return true } + return false } - nuxt.options.pages = isPagesEnabled() + nuxt.options.pages = await isPagesEnabled() // Restart Nuxt when pages dir is added or removed const restartPaths = nuxt.options._layers.flatMap(layer => [ join(layer.config.srcDir, 'app/router.options.ts'), join(layer.config.srcDir, layer.config.dir?.pages || 'pages') ]) - nuxt.hooks.hook('builder:watch', (event, path) => { + nuxt.hooks.hook('builder:watch', async (event, path) => { const fullPath = join(nuxt.options.srcDir, path) if (restartPaths.some(path => path === fullPath || fullPath.startsWith(path + '/'))) { - const newSetting = isPagesEnabled() + const newSetting = await isPagesEnabled() if (nuxt.options.pages !== newSetting) { console.info('Pages', newSetting ? 'enabled' : 'disabled') return nuxt.callHook('restart')