Hello everyone, I am salted fish, a salty can be salty, but still want to jump a few dream of salted fish ^_^.

What is the require. The context

A webpack-specific method that fetches a specific context by executing require.context for more fine-grained module import, mainly used to automate module import.

Parameter configuration

Require. context(directory: String, /* path */ includeSubdirs: Boolean /* Optional, whether to find subdirectories, default is true */, filter: RegExp /* Optional regex for the type of file to find, default is /^\.\/.*$/, all files */, mode: The String / * optional, 'sync' | 'eager' | 'weak' | 'lazy' | 'lazy - once, the default value is' sync' * /)Copy the code

The demo sample

Let’s take global component registration as an example

Component folder Components directory:

Index.js file under components:

import Vue from "vue"; import upperFirst from "lodash/upperFirst"; import camelCase from "lodash/camelCase"; const PREFIX = "gs-"; Const requireContext = require.context(// the relative path of its component directory "./", // Whether to query its subdirectory true, // the regular expression matching the underlying component file name /^\.\/(? :[a-z][^/]*\/)([A-Z]\w+)\.vue$/ ); Requirecontext.keys ().foreach ((fileName) => {// let componentConfig = {}; try { componentConfig = requireContext( fileName.replace(/\/[A-Z]\w+\.vue$/, "/index.js") ); } catch (e) { componentConfig = requireContext(fileName); } let componentName = upperFirst(camelCase(// strip filename.replace (/^\.\/? .*\/([A-Z]\w+)\.vue$/, `${PREFIX}$1`) ) ); Vue.componentname (componentName, // If the componentoption is exported by 'export default', // then '. Default 'is preferred, // otherwise, the module is reverted to the root. componentConfig.default || componentConfig ); });Copy the code

At this point, the require.context method is used to automatically register components globally, and any new components need to be written in the components directory.

Ps: Components folder description document

1. Use kebab-case mode for all folders. 2. Use PascalCase mode for component file name and corresponding name attributeCopy the code