Home » vue » Dynamic Vue Import from a subfolder

Dynamic Vue Import from a subfolder

Posted by: admin November 26, 2021 Leave a comment

Questions:

I am trying to import all .vue files in a certain subfolder into another component. I know about Global registration of Base components but this does not seem to help me here.

Let’s say I have default Vue component (not the main one) with something like this:

export default {
  components: {
    red: () => import('./panes/red'),
  },
  data() {
    return {
      current: false,
    };
  },

and my file structure is something like:

/src
- main.js
- main.vue
-- components/
-- panes/
--- /red.vue
--- /green.vue
--- /blue.vue
-- SubMain.vue

I am trying to dynamically create the components object for the SubMain.vue folder.

So I try something like this in SubMain.vue:

  import myComponents from './src/components/panes';

  ...

  components: Object.keys(myComponents).reduce((obj, name) => {
    return Object.assign(obj, { [name]: () => import(myComponents[name]) })
  }, {}),

But eslint is giving me errors about Missing file extension and Unable to resolve path to module on the myComponents variable. Yes, I double checked my path and tried other paths. Nothing. I am using the Vue CLI 3 project.

Answers:

If you’re using Webpack, you can use require.context:

import _kebabCase from lodash/kebabCase

const components = require.context('src/panes', true)

components.keys().map(component => {
    // turn './ComponentName.vue' into 'component-name'
    const componentName = _kebabCase(
        component.replace(/^\.\//, '').replace(/\.vue$/, '')
    )
    // register new component globally
    Vue.component(componentName, components(component))
})

###

I don’t think you can import multiple components that way without an index file that aggregates the component import/exports for you. See Import multiple components in vue using ES6 syntax doesn't work