Javascript is required
·
1 min read

Vue Tip: Automatically Import Components

Vue Tip: Automatically Import Components Image

This topic is controversial, but I love it if components are automatically imported. You just have to reference them in your template and they are available. No need to import them manually. This feature is heavily used in Nuxt 3.

I will show you how to implement this feature in Vue 3 using unplugin-vue-components.

Installation & Usage

First, install the plugin:

bash
npm i unplugin-vue-components -D

Next, add it to your vite.config.ts:

1import Components from 'unplugin-vue-components/vite'
2
3export default defineConfig({
4  plugins: [
5    Components({ /* options */ }),
6  ],
7})

Info

The GitHub README contains installation guides for other bundlers such as Rollup or Webpack.

And that's it. Now, you can reference components in your template without importing them manually:

1<script setup lang="ts">
2import HelloWorld from './src/components/HelloWorld.vue' // [!code --]
3
4// other script logic...
5</script>
6
7<template>
8  <div>
9    <HelloWorld msg="Hello Vue 3.0 + Vite" />
10  </div>
11</template>

Demo

Try it yourself in the following StackBlitz project:

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.