Automatically import base components in a Quasar project

published at Nov 21, 2019
#Vuejs#Quasar

A project written in Vuejs, especially the large ones, has lots of base components, like BaseButton, BaseInput, BaseTitle, etc... Those components are often used. If you want to import them automatically in a Quasar project, you could create a boot file to register them globally. Let me show how I did it.

This post is largely inspired by the second pattern taught by Chris Fritz in a vue conference. Please show this video if you want to learn more. I adapted the code to my needs but the basic idea comes from this conference.

Consider you have a working Quasar project, and a tree directory which looks like mine:

Img

Notice my base components are always named in a same way: BaseSomething.vue.

Whenever I need those components in a vue file, I need to import them, register them in it. And I need to repeat this process in every component. It's particularly tedious because those components are used almost in every "higher components".

Let's import base components automatically by creating a boot file:

quasar new boot baseComponentRegistration
// src/boot/baseComponentRegistration.js
const requireComponent = require.context('components', false, /Base[\w]+\.vue$/) // require the base components in the components directory.

export default async ({ Vue }) => {
  requireComponent.keys().forEach(fileName => {
    const componentConfig = requireComponent(fileName)
    const componentName = fileName.replace(/^\.\//, '').replace(/\.vue/, '')

    Vue.component(componentName, componentConfig.default || componentConfig) // register globally the base components in the Vue instance
  })
}

Then register this boot file in your Quasar config file:

// quasar.conf.js
module.exports = function (ctx) {
  return {
    boot: [
      'baseComponentRegistration',

      // ...

    ],

    // ...

  }
}

That's all. Now you can use your base components without worrying about importing them in your vue file.