Nuxt Tip: Use Nuxt Layers to Share Components, Utils, and Configuration Between Your Apps
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:
Then we add it to the modules
section in our nuxt.config.ts
:
Next, we add our BaseComponent
in the components
folder:
For this demo, let's share the layer via NPM. You can easily publish your layer by running the following command:
It will publish the layer with the name
specified in package.json
.
Info
You can share more than components and modules with a Nuxt layer, for example:
- 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:
Then you need to add the dependency to extends
in nuxt.config
:
Info
You can also extend from a local layer or 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 X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Declare and Mutate v-model Props as Normal Variable Using defineModel
Declaring and mutate v-model props as the same as normal variable using the defineModel.
Vue Tip: Effortless Handle Asynchronous Components With Suspense
Suspense components are used to display fallback content when waiting for some sort of asynchronous component to resolve.