require.context
官方文檔指出
It allows you to pass in a directory to search, a flag indicating whether subdirectories should be searched too, and a regular expression to match files against.
意思是它允許你通過(guò)一個(gè)目錄進(jìn)行搜索,flag指定是否搜索子目錄,以及與文件匹配的正則表達(dá)式。
也就是說(shuō) require.context 有三個(gè)參數(shù):
- directory:說(shuō)明需要檢索的目錄
- useSubdirectories:是否檢索子目錄
- regExp: 匹配文件的正則表達(dá)式
examples:
require.context('./test', false, /\.test\.js$/);
context module API
官方文檔指出
A context module exports a (require) function that takes one argument: the request.
The exported function has 3 properties: resolve, keys, id.
resolve is a function and returns the module id of the parsed request.
keys is a function that returns an array of all possible requests that the context module can handle.
id is the module id of the context module. This may be useful for module.hot.accept
意思是該上下文到處一個(gè)必須的函數(shù),并且這個(gè)函數(shù)接受一個(gè)請(qǐng)求的參數(shù).
導(dǎo)出的函數(shù)有3個(gè)屬性:resolve、keys和id.
- resolve是一個(gè)函數(shù),返回解析請(qǐng)求的模塊ID。
- keys是一個(gè)函數(shù),返回上下文模塊可以處理的所有可能請(qǐng)求的數(shù)組.
- id是上下文模塊的模塊ID。 這可能對(duì)module.hot.accept有用
var cache = {};
function importAll (r) {
r.keys().forEach(key => cache[key] = r(key));
}
importAll(require.context('../components/', true, /\.js$/));
例如導(dǎo)出當(dāng)前目錄文件下的所有js文件并且不包含該index.js文件
首先創(chuàng)建兩個(gè)測(cè)試文件index.js和test.js
//index.js
var cache = {};
function importAll (r) {
r.keys().forEach(key => {
if(key === './index.js') return
cache[key] = r(key).defalut
});
}
importAll(require.context('.', false, /\.js$/));
console.log(cache) //可以看下cache現(xiàn)在是什么樣子
export default cache