es6 模組
commonjs
amd
如果您的請求包含表達式,將會建立一個內容,因此在編譯時並不知道確切的模組。
範例,假設我們有包含 .ejs
檔案的下列資料夾結構
example_directory
│
└───template
│ │ table.ejs
│ │ table-row.ejs
│ │
│ └───directory
│ │ another.ejs
當評估下列 require()
呼叫時
require('./template/' + name + '.ejs');
Webpack 會剖析 require()
呼叫並擷取一些資訊
Directory: ./template
Regular expression: /^.*\.ejs$/
內容模組
會產生一個內容模組。它包含對該目錄中所有模組的參考,這些模組可以使用與正規表示式相符的請求來要求。內容模組包含一個將請求轉換為模組 ID 的對應。
範例對應
{
"./table.ejs": 42,
"./table-row.ejs": 43,
"./directory/another.ejs": 44
}
內容模組還包含一些執行時間邏輯來存取對應。
這表示支援動態要求,但會導致所有相符的模組都包含在套件中。
您可以使用 require.context()
函數建立自己的內容。
它允許您傳入一個目錄進行搜尋,一個標誌表示是否也應搜尋子目錄,以及一個用於比對檔案的正規表示式。
Webpack 在建置時會分析程式碼中的 require.context()
。
語法如下
require.context(
directory,
(useSubdirectories = true),
(regExp = /^\.\/.*$/),
(mode = 'sync')
);
範例
require.context('./test', false, /\.test\.js$/);
// a context with files from the test directory that can be required with a request ending with `.test.js`.
require.context('../', true, /\.stories\.js$/);
// a context with all files in the parent folder and descending folders ending with `.stories.js`.
context 模組匯出一個 (require) 函數,它接收一個參數:請求。
匯出的函數有 3 個屬性:resolve
、keys
、id
。
resolve
是函數,它會傳回已分析請求的模組 ID。keys
是函數,它會傳回陣列,其中包含 context 模組可以處理的所有可能的請求。如果您想要求目錄中的所有檔案或符合模式的檔案,這會很有用,範例
function importAll(r) {
r.keys().forEach(r);
}
importAll(require.context('../components/', true, /\.js$/));
const cache = {};
function importAll(r) {
r.keys().forEach((key) => (cache[key] = r(key)));
}
importAll(require.context('../components/', true, /\.js$/));
// At build-time cache will be populated with all required modules.
id
是 context 模組的模組 ID。這對於 module.hot.accept
可能很有用。