Is it possible to import *.vue files in a folder?

I use this script in a file named "index.js" to "export default all exported default in every file in the current folder" sort of thing:

const files = require.context('.', false, /\.js$/)
const modules = {}
files.keys().forEach((key) => {
  if (key === './index.js') return
  modules[ key.replace(/(\.\/|\.js)/g, '') ] = files(key).default
})
export default modules

Then you can import the whole directory by importing it's name, just like this:

import folder from '../path/to/folder'

I hope this helps.


See the medium post I created

I'll explain it in an in-depth / easy way there.

For a quick answer here.

  • Create a folder (let's say colors folders for example)

  • create and or add your Vue files inside of that folder (sample red.vue, blue.vue, green.vue)

  • add to that folder (colors folder) an index.js containing (This is based on oprogfrogo's answer.).

const files = require.context('.', false, /\.vue$/)
const modules = {}
files.keys().forEach((key) => {
     if (key === './index.js') return
     modules[key.replace(/(\.\/|\.vue)/g, '')] = files(key)
})
export default modules

your directory looks like for example

  • colors/
  • colors/red.vue
  • colors/blue.vue
  • colors/green.vue
  • colors/index.js

then in any component, you can

 import colors from "./colors/index" //location of the folder
 console.log(colors);
 let yourComponent = colors['blue'].default // wil get you that component 

where ['is the file name']

then in your template, you can

<component v-bind:is="yourComponent"></component>

Based on Potray and Fosuze's working answers for easy reference:

const files = require.context('.', false, /\.vue$/)
const modules = {}
files.keys().forEach((key) => {
     if (key === './index.js') return
     modules[key.replace(/(\.\/|\.vue)/g, '')] = files(key)
})
export default modules