Fitch24
Fitch24
NNuxt
Created by Fitch24 on 12/4/2024 in #❓・help
Code splitting and auto-import
How I can split complex layouts/pages to separated components without auto-imports? I have a layout in ~/layouts/default.vue and I want to move header and footer to separate files as standalone components (for code clarify). Header and footer only used in that layout and anywhere else, so placing it in ~/components is a bad idea, because of header and footer will be autoimported in the whoole app (I think, ~/components must be used only for reusable components). If I place header.vue and footer.vue inside ~/layouts near layout file (default.vue), nuxt will interpreate it as a standalone layouts. My solution is to place layout files inside non autoimported folder and reexport it in ~/layouts, so I created folder ~/import/layouts/default and three files header.vue, footer.vue and layout.vue (main layout file where footer and header are manually imported), then I create default.ts inside ~/layouts directory and reexport layout like this:
<script setup lang="ts">
// ~/import/layouts/default/layout.vue
import Header from "./header.vue"
import Footer from "./fotter.vue"
</script>
<template>
<div>
<Header />
<main>
<slot />
</main>
<Footer />
</div>
</template>
<script setup lang="ts">
// ~/import/layouts/default/layout.vue
import Header from "./header.vue"
import Footer from "./fotter.vue"
</script>
<template>
<div>
<Header />
<main>
<slot />
</main>
<Footer />
</div>
</template>
// ~/layouts/default.ts
import { default as DefaultLayout } from '~/import/layouts/default/layout.vue'
export default DefaultLayout
// ~/layouts/default.ts
import { default as DefaultLayout } from '~/import/layouts/default/layout.vue'
export default DefaultLayout
This solution is works fine for layouts but not fully worked for pages. I tried to split some complex pages to separated components (only used on exactly that page, i.e. non reusable), but I failed to use definePageMeta macro. It's just do nothing if I call it in any file that is not inside ~/pages directory. Or working but produce scare warning if I call it before reexport page (inside ~/pages/index.ts) like this:
// ~/pages/index.ts
import { default as MainPage } from '~/import/pages/main/page.vue'
definePageMeta({
layout: 'custom'
})
export default MainPage
// ~/pages/index.ts
import { default as MainPage } from '~/import/pages/main/page.vue'
definePageMeta({
layout: 'custom'
})
export default MainPage
5 replies