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はサポートされていますが、一致するすべてのモジュールがバンドルに含まれる原因となります。
`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`.
コンテキストモジュールは、1つの引数(要求)を取る(require)関数をエクスポートします。
エクスポートされた関数には、`resolve`、`keys`、`id`の3つのプロパティがあります。
これは、ディレクトリ内のすべてのファイル、またはパターンに一致するすべてのファイルをrequireする場合に役立ちます。例
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.