·
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:

import Components from 'unplugin-vue-components/vite' export default defineConfig({ plugins: [ Components({ /* options */ }), ], })

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:

<script setup lang="ts"> import HelloWorld from './src/components/HelloWorld.vue' // [!code --] // other script logic... </script> <template> <div> <HelloWorld msg="Hello Vue 3.0 + Vite" /> </div> </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.