上篇文章給大家介紹了細(xì)說webpack源碼之compile流程-rules參數(shù)處理技巧(1), 細(xì)說webpack源碼之compile流程-入口函數(shù)run
大家可以點(diǎn)擊查看。
第一步處理rule為字符串,直接返回一個(gè)包裝類,很簡單看注釋就好了。
test
然后處理test、include、exclude,如下:
if (rule.test || rule.include || rule.exclude) { // 標(biāo)記使用參數(shù) checkResourceSource("test + include + exclude"); // 沒有就是undefined condition = { test: rule.test, include: rule.include, exclude: rule.exclude }; // 處理常規(guī)參數(shù) try { newRule.resource = RuleSet.normalizeCondition(condition); } catch (error) { throw new Error(RuleSet.buildErrorMessage(condition, error)); }}checkResourceSource直接看源碼:
let resourceSource;// ...function checkResourceSource(newSource) { // 第一次直接跳到后面賦值 if (resourceSource && resourceSource !== newSource) throw new Error(RuleSet.buildErrorMessage(rule, new Error("Rule can only have one resource source (provided " + newSource + " and " + resourceSource + ")"))); resourceSource = newSource;}這個(gè)用于檢測(cè)配置來源的唯一性,后面會(huì)能看到作用,同樣作用的還有checkUseSource方法。
隨后將三個(gè)參數(shù)包裝成一個(gè)對(duì)象傳入normalizeCondition方法,該方法對(duì)常規(guī)參數(shù)進(jìn)行函數(shù)包裝:
class RuleSet { constructor(rules) { /**/ }; static normalizeCondition(condition) { // 假值報(bào)錯(cuò) if (!condition) throw new Error("Expected condition but got falsy value"); // 檢測(cè)給定字符串是否以這個(gè)開頭 if (typeof condition === "string") { return str => str.indexOf(condition) === 0; } // 函數(shù)直接返回 if (typeof condition === "function") { return condition; } // 正則表達(dá)式返回一個(gè)正則的test函數(shù) if (condition instanceof RegExp) { return condition.test.bind(condition); } // 數(shù)組map遞歸處理 有一個(gè)滿足返回true if (Array.isArray(condition)) { const items = condition.map(c => RuleSet.normalizeCondition(c)); return orMatcher(items); } if (typeof condition !== "object") throw Error("Unexcepted " + typeof condition + " when condition was expected (" + condition + ")"); const matchers = []; // 對(duì)象會(huì)對(duì)每個(gè)值進(jìn)行函數(shù)包裝彈入matchers中 Object.keys(condition).forEach(key => { const value = condition[key]; switch (key) { case "or": case "include": case "test": if (value) matchers.push(RuleSet.normalizeCondition(value)); break; case "and": if (value) { const items = value.map(c => RuleSet.normalizeCondition(c)); matchers.push(andMatcher(items)); } break; case "not": case "exclude": if (value) { const matcher = RuleSet.normalizeCondition(value); matchers.push(notMatcher(matcher)); } break; default: throw new Error("Unexcepted property " + key + " in condition"); } }); if (matchers.length === 0) throw new Error("Excepted condition but got " + condition); if (matchers.length === 1) return matchers[0]; return andMatcher(matchers); }}
新聞熱點(diǎn)
疑難解答
圖片精選