Javascript is required
·
2 min read

Nuxt Tip: Use Nuxt Layers to Share Components, Utils, and Configuration Between Your Apps

Nuxt Tip: Use Nuxt Layers to Share Components, Utils, and Configuration Between Your Apps Image

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:

To create a new Nuxt layer, visit nuxt.new and select the Layer starter:

nuxt.new Layer

To add the Tailwind module, we follow the getting started steps from the module documentation:

First, we install the module:

bash
pnpm add -D @nuxtjs/tailwindcss

Then we add it to the modules section in our nuxt.config.ts:

nuxt.config.ts
1export default defineNuxtConfig({
2  modules: ['@nuxtjs/tailwindcss'],
3})

Next, we add our BaseComponent in the components folder:

BaseComponent.vue
1<template>
2  <button class="rounded-md border-2 bg-blue-400 p-2 text-white">
3    <slot />
4  </button>
5</template>

For this demo, let's share the layer via NPM. You can easily publish your layer by running the following command:

bash
pnpm publish --access public

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 and utils/ 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:

bash
pnpm add -D @mokkapps/nuxt-layer-demo

Then you need to add the dependency to extends in nuxt.config:

nuxt.config.ts
1defineNuxtConfig({
2  extends: '@mokkapps/nuxt-layer-demo',
3})

Info

You can also extend from a local layer or a Git repository:

nuxt.config.ts
1export default defineNuxtConfig({
2  extends: [
3    '../base', // Extend from a local layer
4    '@my-themes/awesome', // Extend from an installed npm package
5    'github:my-themes/awesome#v1', // Extend from a git repository
6  ],
7})

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:

I will never share any of your personal data. You can unsubscribe at any time.