在用vue開發的過程當中,咱們可能會使用import引入文件,但須要引入多個的時候就會變得繁瑣起來,這時咱們能夠使用require.context去動態引入多個文件。前端
stackoverflow上的解釋很是明確:vue
require.context is a special feature supported by webpack's compiler that allows you to get all matching modules starting from some base directory. The intention is to tell webpack at compile time to transform that expression into a dynamic list of all the possible matching module requests that it can resolve, in turn adding them as build dependencies and allowing you to require them at runtime.webpack
In short, you would use require.context in the exact same situation when in Node.js at runtime you would use globs to dynamically build a list of module paths to require. The return value is a callable object that behaves like require, whose keys contain the necessary module request data that can be passed to it as an argument to require the module.web
There are several ways you can use it, but I think the two most common use cases are to either automagically require some well-known kind of modules (e.g. you just add some.test.js test module and in some module you use require.context to dynamically discover all the tests, thus not having to document and remember to do it manually every time you add a new test module) or to load static assets in the repository to emit files to the build output (new webpack users coming from other build tools are usually surprised that their images, fonts, audio files and other assets do not appear in the output unless they are required from some module).express
注意上面提到的「多個文件」並不要求特定類型的文件,所以,這個工具是很是有用的。在開發SPA前端過程當中,常常須要以下圖所示的任務,即把使用大量的import把子組件注入到一個視圖中:
segmentfault
此時,逐個導入費力並且容易出問題,特別是在需求不斷變化時。app
require.context(directory, useSubdirectories, regExp)
【參數含義】less
因而,針對上圖中須要使用Import加載大量文件的需求(項目中可能還會存在不少相似需求),能夠使用以下方案來簡化:ide
import Vue from 'vue' import upperFirst from 'lodash/upperFirst' import camelCase from 'lodash/camelCase' const requireComponent = require.context( '@/components/base', true, /\.vue$/, ) requireComponent.keys().forEach(fileName => { const componentConfig = requireComponent(fileName) const componentName = upperFirst( camelCase(fileName.replace(/^\.\//, '').replace(/\.\w+$/, '')), ) // 註冊組件,傳入一個擴展過的構造器or 對象 Vue.component(`Base${componentName}`, componentConfig.default || componentConfig) })
上面代碼的整體功能描述是:工具