How to dynamically load a Vue component after using require.context?
Asked Answered
P

2

8

Currently I am loading all of my Vue components with require.context, this searches my components directory with a regex for .vue files. This works fine but I would like to load async components as well with dynamic imports.

Currently when I use require.context all files get loaded so even If I want to use a dynamic import my file is already loaded and nothing happens.

I need a way to exclude certain files from my require.context call. I cannot dynamically create a regex because this does not work with require.context.

// How I currently load my Vue components.

const components = require.context('@/components', true, /[A-Z]\w+\.vue$/);

components.keys().forEach((filePath) => {
    const component = components(filePath);
    const componentName = path.basename(filePath, '.vue');

    // Dynamically register the component.
    Vue.component(componentName, component);
});

// My component that I would like to load dynamically.
Vue.component('search-dropdown', () => import('./search/SearchDropdown'));

It seems the only way to do this is either manually declare all my components, which is a big hassle.

Or to create a static regex that skips files that have Async in their name. Which forces me to adopt a certain naming convention for components that are async. Also not ideal.

Would there be a better way to go about doing this?

Parlance answered 25/4, 2018 at 13:9 Comment(0)
B
5
const requireContext = require.context('./components', false, /.*\.vue$/)

const dynamicComponents = requireContext.keys()
    .map(file =>
        [file.replace(/(^.\/)|(\.vue$)/g, ''), requireContext(file)]
    )
    .reduce((components, [name, component]) => {
        components[name] = component.default || component
        return components
    }, {})
Brendis answered 4/4, 2019 at 7:33 Comment(0)
C
1

Works with Vue 2.7 and Vue 3.

The lazy mode forces requireContext to return a promise.

const { defineAsyncComponent } = require('vue')

const requireContext = require.context('./yourfolder', true, /^your-regex$/, 'lazy')
module.exports = requireContext.keys().reduce((dynamicComponents, file) => {
  const [, name] = file.match(/^regex-to-match-component-name$/)
  const promise = requireContext(file)
  dynamicComponents[name] = defineAsyncComponent(() => promise)
  return dynamicComponents
}, {})

You can also use defineAsyncComponent({ loader: () => promise }) if you want to use the extra options of defineAsyncComponent.

Conversazione answered 29/11, 2022 at 0:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.