fix(nuxt): allow pages:extend to enable pages module (#20806)

This commit is contained in:
Dario Ferderber 2023-05-15 14:47:30 +02:00 committed by GitHub
parent ce84c9b44f
commit ec9dcdb093
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 6 deletions

View File

@ -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`);
})
}

View File

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