Are you still introducing high frequency components like this

Use require.context to implement front-end engineering automation quickly into projects

Require. context is what?

A Webpack API, which is used to automatically import modules by executing require.context. In front-end engineering, if many modules are imported from a folder, this API can be used, it will iterate through the specified files in the folder, and then automatically import, so that The import module does not need to be explicitly called every time

Analysis the require. The context

Require. context takes three arguments

  • Directory {String} – Read the file path
  • UseSubdirectories {Boolean} – Whether to traverse a file subdirectory
  • RegExp {regExp} – Matches the re of the file
Syntax: require.context(directory, useSubdirectories =false, regExp = /^.//);
Copy the code

Require. Context () in index.js under components'./common'.false, /\.vue$/);
Copy the code

You can see that the keys() method returns an array of the names of the matching files
Vue.component(component name,options) options are objects {data:function(){},
template:''
}
Copy the code

ChangeStr capitalizes the first letter of a string (component registration usually starts with an uppercase letter)// import Demo from ‘@/components/ Demo ‘
Let config = requireComponent(fileName)

We are in main.js

Finally, the global injection component completes

// import Vue from "vue";
functionChangeStr (STR) {// Capitalize the first letterreturnstr.charAt(0).toUpperCase() + str.slice(1); } const requireComponent = require.context() const requireComponent = require.context()"./common".false, /\.vue$/); console.log(requireComponent.keys()); / / /"./child1.vue"."./child2.vue"]
const install = (Vue) => {
  requireComponent.keys().forEach((fileName) => {
    let config = requireComponent(fileName);
    let componentName = changeStr(
      fileName.replace(/^\.\//, "").replace(/\.\w+$/, "")); console.log(config); // console.log(componentName); //Child1 Child2 Vue.component(componentName, config.default || config); }); };export default {
  install,
};

Copy the code