SoFunction
Updated on 2025-04-05

How to use automatic introduction of components in Vue

In our project development, we often need to import or export various modules. So is there any way to simplify this introduction or export operation? The answer is yes, let me introduce it to you below

yeswebpackAn API provided for creating context, i.e. a set of modules with the same context.

useMultiple modules can be loaded conveniently, and the loading order and dependencies of the modules can be flexibly controlled.

In the past, we introduced components through import

import A from 'components/A'
import B from 'components/B'
import C from 'components/C'
import D from 'components/D'

This is very painful, because every time a component is added, you may have to write such a sentence. Can such regular things be completed through automation?

(Requires the version of vue-cli3+)

(directory, useSubdirectories, regExp)
  • directory: The file path to look for
  • useSubdirectories: Whether to look for subdirectories
  • regExp: Regular to match the file

1. Create a file under the components file

const requireComponent = ('./', true, /\.vue$/)
const install = (Vue) => {
    if () return
    
    ().forEach(element => {
        const config = requireComponent(element)
        if (config && ) {
            const componentName = 
            (componentName,  || config)
        }
    });
}
if (typeof window !== 'undefined' && ) {
    install()
}
export default {
    install
}

Introduce this js

import install from './compoents'
(install)

Summarize

We can introduce files through automated means.
In fact, we are not limited to components. All module files are common within the route, such as routing and interface encapsulation modules, which can be used.

This is the article about the introduction of the method of using automatic components in Vue. For more information about automatic components introduction of Vue, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!