Auto-importing custom components in VueJS

Vuejs Mar 27, 2020

There are just 4 simple steps to have an auto-importer for your custom components in VueJS. Presumably, you have created your project using VueCLI3, but it is not mandatory.

I am using the eClassTools codebase for screenshots when on commit 5ede8846237e8a591354542fcae7a4441e6b6f6a, so if you want, you can check out the exact files that were shown here.

Step 1 - create your custom components

Mind the "name" property! All custom components need unique names.

Custom VueJS components
Custom components with unique names

Step 2 - Create the components auto-loader script

I've created that script in my /src/plugins folder, but you can create it anywhere you want.

Auto-loading script in plugins directory
import Vue from 'vue'

const components = require.context('../components', true, /\/[a-zA-Z0-9]+\.vue$/)
components.keys().forEach(el => {
  const name = String(components(el).default.name).toLowerCase()
  Vue.component(`c-${name}`, components(el).default)
})
Auto-loader script content

With this config, all auto-imported components will be prefixed with "c-" which represents "custom" (as custom component). If we were to change that to "custom-", we'd have to change the following line

Vue.component(`custom-${name}`, components(el).default)
"custom-" prefix for component names

Remember to update the components folder path if you decided to have the auto-loader script in another location. If we were to have our components in a folder named "customElements, we'd have to change the following

const components = require.context('../customElements', true, /\/[a-zA-Z0-9]+\.vue$/)

Step 3 - Loading the auto-loader script

Now we just need to import the script to our application. We will do that in the main.js file which is the entrypoint of our application. Just add the following line before the new Vue({ ... }) method is called.

import './plugins/console'

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import vuetify from './plugins/vuetify'
import i18n from './plugins/i18n'
import './registerServiceWorker'
import './plugins/preventContextmenu'
import './plugins/componentsAutoLoad' // <== HERE WE IMPORT IT
import './plugins/dataTypeString'
import 'roboto-fontface/css/roboto/roboto-fontface.css'
import '@mdi/font/css/materialdesignicons.css'

Vue.config.productionTip = false

new Vue({
  router,
  store,
  vuetify,
  i18n,
  render: h => h(App)
}).$mount('#app')
Importing the auto-loader script (line 

Step 4 - using the auto-imported components

Now all you have to do is use the component. I, for example, have used them in the App.vue file without ever manually importing them.

<template>
  <v-app>

    <c-sidebar />

    <v-content fill-height>
      <transition
        name="fade"
        mode="out-in"
        appear
      >
        <router-view />
      </transition>
    </v-content>

    <c-snackbars />
    <c-updatesnack />

  </v-app>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'App',
  watch: {
    appDarkMode (val, old) { this.updateDark(val) }
  },
  computed: {
    ...mapState('auth', { user: 'user' }),
    appDarkMode () {
      if (typeof this.user === 'object' && this.user !== null && typeof this.user.appDarkMode === 'string') return this.user.appDarkMode
      else return 'unset'
    },
    darkMatch () { return window.matchMedia('(prefers-color-scheme: dark)') }
  },
  mounted () {
    this.darkMatch.addListener((e) => this.updateDark(e.val))
    this.updateDark()
  },
  methods: {
    updateDark (val) {
      if (
        typeof val === 'string' &&
        (val === 'no' || val === 'yes')
      ) {
        this.$vuetify.theme.dark = val === 'yes' ? Boolean(true) : Boolean(false)
      } else {
        this.$vuetify.theme.dark = this.darkMatch.matches
      }
    }
  }
}
</script>
<style>
@import './assets/css/master.css';
.fade-enter-active, .fade-leave-active { transition: opacity 0.2s }
.fade-enter, .fade-leave-active { opacity: 0 }
</style>
The App.vue from eClassTools project - using auto-imported components

Ending thought

Thank you for reading this short little snippet of my findings. I hope it helped you at least a lil' bit.

Enjoy your time in quarantine, because deep inside, we all know it really isn't that quacking awful afterall - I mean, it could be much worse. And you all get to work on a project that you wanted to finish months ago.

A poor attempt of using a meymey in a post

Aljaz S.

I am a student and a web developer