·
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
export default defineNuxtConfig({ modules: ['@nuxtjs/tailwindcss'], })

Next, we add our BaseComponent in the components folder:

BaseComponent.vue
<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:

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
defineNuxtConfig({ extends: '@mokkapps/nuxt-layer-demo', })

Info

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

nuxt.config.ts
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 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.