Nuxt Tip: Use Nuxt Layers to Share Components, Utils, and Configuration Between Your Apps
Michael Hoffmann
@mokkapps
Nuxt 3 provides a powerful core feature that allows you to share components, utils, and configurations between your Nuxt 3 applications. These so-called layers are almost identical to a standard Nuxt application, let's take a look at an example.
Create Layer
For this demo, we would like to share two things from our Nuxt layer:
- the Nuxt Tailwind module
- a
BaseButton
component
To create a new Nuxt layer, visit nuxt.new and select the Layer
starter:
To add the Tailwind module, we follow the getting started steps from the module documentation:
First, we install the module:
pnpm add -D @nuxtjs/tailwindcss
Then we add it to the modules
section in our nuxt.config.ts
:
export default defineNuxtConfig({
modules: ['@nuxtjs/tailwindcss'],
})
Next, we add our BaseComponent
in the components
folder:
<template>
<button class="rounded-md border-2 bg-blue-400 p-2 text-white">
<slot />
</button>
</template>
For this demo, let's share the layer via NPM. You can easily publish your layer by running the following command:
pnpm publish --access public
It will publish the layer with the name
specified in package.json
.
- reusable configuration presets in nuxt.config and app.config
- utility and composable functions inside
/composables
andutils/
directories - Nuxt themes
- Nuxt module presets
The code for this demo Nuxt layer is available at StackBlitz:
Use Layer
Now let's use our Nuxt layer in a Nuxt application. The first step is to install the NPM package of our Nuxt layer:
pnpm add -D @mokkapps/nuxt-layer-demo
Then you need to add the dependency to extends
in nuxt.config
:
defineNuxtConfig({
extends: '@mokkapps/nuxt-layer-demo',
})
export default defineNuxtConfig({
extends: [
'../base', // Extend from a local layer
'@my-themes/awesome', // Extend from an installed npm package
'github:my-themes/awesome#v1', // Extend from a git repository
],
})
Without any further configurations, you can now use BaseButton
and Tailwind classes in our Nuxt application.
The code for this Nuxt application is interactively available at StackBlitz:
Video
If you prefer visual content, this video from Learn Vue shows the power of Nuxt Layers:
If you liked this Vue tip, follow me on BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :
Vue Tip: Effortless Handle Asynchronous Components With Suspense
Vue Tip: Declare and Mutate v-model Props as Normal Variable Using defineModel