vue.jsnuxt.js

Does a Nuxt layout requires special arrangements for single file components?


I created a Nuxt project from scratch to learn about layouts.

I changed app.vue to

<template>
  <NuxtLayout>
    <NuxtPage />
  </NuxtLayout>
</template>

In layouts I added the file default.vue:

<template>
    <div>
        <!-- set here how all the pages will look like -->
        this is the default layout
        <slot />
    </div>
</template>

Finally I created eat.vue in pages:

<template>
    <div>
        eat section
    </div>
</template>

When going to http://localhost:3000/eat (EDIT: I initially forgot to add the eat part but this does not change anything - in no case should a 500 be displayed) I get a 500 error (this is what is displayed on the web page):

500

[vite-node] [plugin:vite:vue] [SyntaxError] /pages/eat.vue?macro=true

at /pages/eat.vue?macro=true
at Object.parse$1 [as parse] (C:\proj\test-nuxt-layouts\node_modules\@vue\compiler-sfc\dist\compiler-sfc.cjs.js:1864:7)
at createDescriptor (/C:\proj\test-nuxt-layouts/node_modules/@vitejs/plugin-vue/dist/index.mjs:71:43)
at transformMain (/C:\proj\test-nuxt-layouts/node_modules/@vitejs/plugin-vue/dist/index.mjs:2430:34)
at TransformPluginContext.transform (/C:\proj\test-nuxt-layouts/node_modules/@vitejs/plugin-vue/dist/index.mjs:2994:16)
at /C:\proj\test-nuxt-layouts/node_modules/vite-plugin-inspect/dist/index.mjs:1128:26
at plugin. (/C:\proj\test-nuxt-layouts/node_modules/vite-plugin-inspect/dist/index.mjs:1115:14)
at EnvironmentPluginContainer.transform (/C:\proj\test-nuxt-layouts/node_modules/vite/dist/node/chunks/dep-ByPKlqZ5.js:47631:19)
at async loadAndTransform (/C:\proj\test-nuxt-layouts/node_modules/vite/dist/node/chunks/dep-ByPKlqZ5.js:41318:27)

In the Nuxt output, I see

 ERROR  Pre-transform error: At least one <template> or <script> is required in a single file component. C:\proj\test-nuxt-layouts/pages/eat.vue              18:33:55
  Plugin: vite:vue
  File: C:\proj\test-nuxt-layouts/pages/eat.vue

I am kinda lost because eat.vue does have a <template> -- what did I miss?


Solution

  • It looks like the issue was not in the layout system but with my understanding of the documentation warning about single root components:

    Unlike other components, your layouts must have a single root element to allow Nuxt to apply transitions between layout changes - and this root element cannot be a <slot />.

    I used

    <template>
       <h1>this is the main page /</h1>
    </template>
    

    but it should have been

    <template>
        <div>
            <h1>this is the main page /</h1>
        </div>
    </template>
    

    An extra div was required, it seems that having the h1 tag as the "root" was not enough.