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.

Global

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

Local

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
   './components',
   // Whether or not to look in subfolders
   false,
   // The regular expression used to match base component filenames
   /Base[A-Z]\w+\.(vue|js)$/
)

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

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

// Register component globally
Vue.component(
   componentName,
     // 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.

Source: https://github.com/chrisvfritz/vue-enterprise-boilerplate/blob/master/src/components/_globals.js

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.