Import all components from a specific folder

Hi everyone,

I wonder if there’s a way to import all components from a specific folder.

Instead of having something list like this:

import component1 from '@/components/module/component1'
import component2 from '@/components/module/component2'
import component3 from '@/components/module/component3'

use this (which doesn’t work):

import * as components from '@/components/module'

Thanks in advance,

1 Like

Create index.js file in the components/module folder:

import component1 from './component1'
import component2 from './component2'
import component3 from './component3'

export default {
  component1, component2, component3
}

Then import batch of components as:

import components from '@/components/module'
3 Likes

How would you pass them to the view model then?

new Vue({
 components : components
}

Bear in mind you can also globally register components, which saves you importing and declaring them everywhere they are used.

I use this online tool to quickly create the boilerplate:

Just drag the files from your desktop to the left hand pane to get the filenames in.

You can edit the “path” parameter in the editing pane to change the output path as required:

Though the question already has been answered and is a year old.
But maybe it helps someone.

You can use a computed property for this.
This not only enables you to import multiple components, but files aswesll (e.g. MD)

  computed: {
    comps () {
      const components = require.context('@/your/path', false, /yourRegex$/)
      return components .keys().map(x => components (x))
    }
  },

following this pattern you can dynamically import components aswell:

computed: {
  comp () {
      return () => import(`@/components/${this.componentName}.vue`)
  }
}

and then use it like:

<template>
    <component :is="comp"></component>
</template>
3 Likes

Use require.context

1 Like

Thanks really usefull :slight_smile: :wave::kissing_heart:

This is very interesting an approach for loading components. Is there a way to do this with classes you import as well? We use a list with imports like

import ImageModule from "./classes/ImageModule";
window.ImageModule = ImageModule;
import LogoModule from "./classes/LogoModule";
...

and would prefer to import from a directory to for new module components. With require.context we could import the Vue components, but what about the classes needed?

I noticed nobody answered the question exactly.

This is how you do it in a Vue plugin: (example is for filters)

const filterFiles = require.context('@/filters', true, /\.js$/);
const filters = [];
for (const file of filterFiles.keys()) {
  const name = file.replace(/^\.\//, '').replace(/\.\w+$/, '');
  filters.push([name, import(`@/filters/${name}.js`)]);
}

export default {
  async install(Vue) {
    for (const [file, exported] of filters) {
      Vue.filter(file, (await exported).default);
    }
  }
}