·
1 min read
Vue Tip: Automatically Import Components
MH
Michael Hoffmann
@mokkapps
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:
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 */ }),
],
})
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'
// 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 BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :