Register Global Vue Components using Webpack

If you have ever worked on a VueJs application, you probably have noticed there are several ways to register Vue components. You have the ability to manually register each component globally or locally. This will work but is very repetitive and not necessary.


Vue.component('my-component-name', { /* ... */ })


components: {
   'component-a': ComponentA,
   'component-b': ComponentB

Fortunately, if you are able to use Webpack, it has a neat method called require.context that will allow you to globally register these components.

Automatically Register Global Components

import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

const requireComponent = require.context(
   // The relative path of the components folder
   // Whether or not to look in subfolders
   // The regular expression used to match base component filenames

requireComponent.keys().forEach(fileName => {
   // Get component config
   const componentConfig = requireComponent(fileName)

   // Get PascalCase name of component
   const componentName = upperFirst(
      // Strip the leading `./` and extension from the filename
      fileName.replace(/^\.\/(.*)\.\w+$/, '$1')

// Register component globally
     // Look for the component options on `.default`, which will
     // exist if the component was exported with `export default`,
     // otherwise fall back to module's root.
     componentConfig.default || componentConfig


Globally registering your components will save you time and will help keep your code organized.

Be sure to check out @chrisvfritz’s Vue Enterprise Boilerplate project for more tips and tricks like this.


Thanks for reading. Make sure you follow me on Twitter to stay up to date on the progress of my side projects T.LYWeather Extension, and Link Shortener Extension. If you are interested in the tech I use daily, check out my uses page.  

Leave a Reply

Your email address will not be published. Required fields are marked *