background

In the daily import of components, modules, in fact, the format of the directory is similar, can be one click to import all? We can do this by looking at require.context. A version of VUE-CLI3 + is required.

require.context

If you happen to use Webpack (or webpack’s Vue CLI 3+ internally), you can use require.context to register only these very generic base components globally — from the Vue official

1. In-component – Automation introduction

directory

  • The component directory has two layers, and due to the specific nature of the project, there are almost 30 components, which can be very troublesome to introduce one by one

  • The e introduction of tradition, in case there is a lot of trouble.
import BaseButton from './BaseButton.vue'
import BaseIcon from './BaseIcon.vue'
import BaseInput from './BaseInput.vue'

export default {
  components: {
    BaseButton,
    BaseIcon,
    BaseInput
  }
}
Copy the code

Automated import code

  • Introduced within the component
const requireComponent = require.context(
    // The relative path of its component directory, which depends on the actual directory
    './companyModel'.// Whether to query subdirectories, I have two layers here, so true
    true.// A regular expression that matches the name of the underlying component file
    /\.vue$/
)

let modules = {} // Component module

requireComponent.keys().forEach(ele= >{
  let key = ele.split('/') [2]
  key = key.substring(0, key.length-4) Vue, PD1,PD2,PD3,ST1...
  modules[key] = requireComponent(ele).default // Module instance assignment
})
// Finally into the component
export default {
   components: modules,
   data(){}}Copy the code

2. Automatic introduction of VUEX – module

  • It’s kind of like a component,vuexModule must beexport

directory

  • A very traditional vuex directory

Automated import code

  • The index in js
let ms = require.context('./modules'.false./\.js$/) // There is only one layer, so it is false, matching js
let modules = {}
ms.keys().forEach(ele= > {
  let n = ele.substring(2, ele.length - 3) // Get the file name and remove the suffix
  modules[n] = ms(ele).default
})

export default new Vuex.Store({
  modules,
})

Copy the code

3, summarize

We can import files automatically by requiring. Context. In fact, we are not only limited to components, routing, all module files are common, such as routing, interface encapsulation module, can be used.