Skip to content
Advertisement

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

I hate repeating things in code. For now I am importing vue files like this in my main.js.

import Default     from '../../src/components/default.vue';
import Home        from '../../src/components/home.vue';
import hakkinda    from '../../src/components/hakkinda.vue';
import projeler    from '../../src/components/projeler.vue';
import servisler   from '../../src/components/servisler.vue';
import yetenekler  from '../../src/components/yetenekler.vue';
import yetenek     from '../../src/components/yetenek.vue';
import referanslar from '../../src/components/referanslar.vue';
import iletisim    from '../../src/components/iletisim.vue';

Is there a way to do same thing with less lines? Could be great if I can assign variable name from filename. Can PHP help about it? But then how to compile main.js? I did not figured out.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement