Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

Vue + Webpack automates the introduction module

In the development of medium and large projects, a large function will be divided into small functions, which can not only facilitate module reuse, but also make the module clear and easier to maintain later projects.

As with API files, modules are divided by function. When combining, you can use require.context to import all module files in a folder at once, rather than importing module files one by one. Whenever a new module file is added, it only needs to be concerned with writing the logic and exposing the module. Require.context will help us introduce it automatically.

Note that require.context is not native, but is provided by Webpack. At build time, WebPack parses it in the code.

let importAll = require.context('./modules'.false./\.js$/)

class Api extends Request{
    constructor(){
        super(a)// importall.keys () is the module path array
        importAll.keys().map(path= >{
            // Compatibility processing:.default obtains the content exposed by the ES6 specification;
            // The latter gets the content exposed by the commonJS specification
            let api = importAll(path).default || importAll(path)
            Object.keys(api).forEach(key= > this[key] = api[key])
        })
    }
}

export default new Api()
Copy the code

The require. The context parameter:

  • Folder path
  • Whether to recursively look for modules under subfolders
  • Module matching rules, generally match file name extensions

You can use this method for any scenario that requires batch introduction. Include some common global components, just add components to the folder can be used, no need to register. If you haven’t used a friend yet, be sure to know that simple, practical and efficient.

Vue — Elegant registry component

Plug-ins are usually used to add global functionality to a Vue. Vue-router and vuex are registered through vue. use. Vue.use is automatically called internally looking for the install method and takes the Vue constructor as the first argument.

Generally, when using component libraries, load on demand is adopted in order to reduce package size.

Importing components one by one in an entry file will make Main.js bigger and bigger, and for modular development purposes, it is best to wrap it in a separate configuration file. With vue. use, in the entry file can be used at a glance.

First we set up an intermediate file

config.js

import {
  Backtop,
  Button
} from 'element-ui'

const components = {
  Backtop,
  Button
}

const componentsHandler = {
  install(Vue){
    Object.keys(components).forEach(key= > Vue.use(components[key]))
  }
}

export default componentsHandler
Copy the code

main.js:

import Vue from 'vue'
import elementCompoents from '@/config/config'

Vue.config.productionTip = false

Vue.use(elementCompoents)

new Vue({
  render: h= > h(App)
}).$mount('#app')
Copy the code

Vue asynchronous components

In large applications, we may need to break the application into smaller code blocks and load a module from the server only when needed. For simplicity, Vue allows you to define your component as a factory function that asynchronously parses your component definition. Vue fires the factory function only when the component needs to be rendered, and caches the result for future re-rendering

Vue.component('async-example'.function (resolve, reject) {
  setTimeout(function () {
    // Pass the component definition to the 'resolve' callback
    resolve({
      template: '
      
I am async!
'
})},1000)})Copy the code

The factory function receives a resolve callback, which is called when you get the component definition from the server. You can also call reject(Reason) to indicate a load failure. SetTimeout here is for demonstration purposes, and it’s up to you to retrieve the component.

With local registrations, you can also provide a function that returns a Promise directly:

'my-component': () = > import('./my-async-component')
Copy the code