From 4ce6bc244c4af7d475b8f068cf7dbd22ccf5c33a Mon Sep 17 00:00:00 2001 From: Luke Nelson Date: Thu, 23 Nov 2023 21:12:28 +0000 Subject: [PATCH] feat(nuxt): warn when page uses a layout without `` (#24116) --- .../nuxt/src/app/components/nuxt-layout.ts | 4 ++++ .../src/app/plugins/check-if-layout-used.ts | 21 +++++++++++++++++++ packages/nuxt/src/core/nuxt.ts | 5 +++++ 3 files changed, 30 insertions(+) create mode 100644 packages/nuxt/src/app/plugins/check-if-layout-used.ts diff --git a/packages/nuxt/src/app/components/nuxt-layout.ts b/packages/nuxt/src/app/components/nuxt-layout.ts index 01a682dca2..e50186d65b 100644 --- a/packages/nuxt/src/app/components/nuxt-layout.ts +++ b/packages/nuxt/src/app/components/nuxt-layout.ts @@ -57,6 +57,10 @@ export default defineComponent({ const done = nuxtApp.deferHydration() + if (import.meta.dev) { + nuxtApp._isNuxtLayoutUsed = true + } + return () => { const hasLayout = layout.value && layout.value in layouts if (import.meta.dev && layout.value && !hasLayout && layout.value !== 'default') { diff --git a/packages/nuxt/src/app/plugins/check-if-layout-used.ts b/packages/nuxt/src/app/plugins/check-if-layout-used.ts new file mode 100644 index 0000000000..2c79642b6e --- /dev/null +++ b/packages/nuxt/src/app/plugins/check-if-layout-used.ts @@ -0,0 +1,21 @@ +import { defineNuxtPlugin } from '../nuxt' +import { onNuxtReady } from '../composables/ready' + +// @ts-expect-error virtual file +import layouts from '#build/layouts' + +export default defineNuxtPlugin({ + name: 'nuxt:checkIfLayoutUsed', + setup (nuxtApp) { + function checkIfLayoutUsed () { + if (!nuxtApp._isNuxtLayoutUsed && Object.keys(layouts).length > 0) { + console.warn('[nuxt] Your project has layouts but the `` component has not been used.') + } + } + if (import.meta.server) { + nuxtApp.hook('app:rendered', checkIfLayoutUsed) + } else { + onNuxtReady(checkIfLayoutUsed) + } + } +}) diff --git a/packages/nuxt/src/core/nuxt.ts b/packages/nuxt/src/core/nuxt.ts index 40a1a265d1..132c8437f4 100644 --- a/packages/nuxt/src/core/nuxt.ts +++ b/packages/nuxt/src/core/nuxt.ts @@ -159,6 +159,11 @@ async function initNuxt (nuxt: Nuxt) { addWebpackPlugin(() => DevOnlyPlugin.webpack({ sourcemap: !!nuxt.options.sourcemap.server || !!nuxt.options.sourcemap.client })) } + if (nuxt.options.dev) { + // Add plugin to check if layouts are defined without NuxtLayout being instantiated + addPlugin(resolve(nuxt.options.appDir, 'plugins/check-if-layout-used')) + } + // Transform initial composable call within `