webpack之require.context

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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容