コンテキストとは、require('./locale/' + name + '.json') などの 式を使用した require を指します。このような式に遭遇すると、webpack はディレクトリ ('./locale/') と正規表現 (/^.*\.json$/) を推測します。name はコンパイル時には不明であるため、webpack はすべてのファイルをバンドル内のモジュールとして含めます。
ContextReplacementPlugin を使用すると、推測された情報をオーバーライドできます。このプラグインを設定するにはさまざまな方法があります。
new webpack.ContextReplacementPlugin(
resourceRegExp: RegExp,
newContentResource?: string,
newContentRecursive?: boolean,
newContentRegExp?: RegExp
)リソース (ディレクトリ) が resourceRegExp に一致する場合、プラグインは、デフォルトのリソース、再帰フラグ、または生成された正規表現を、それぞれ newContentResource、newContentRecursive、または newContextRegExp に置き換えます。newContentResource が相対パスの場合、前のリソースからの相対パスとして解決されます。
モジュールの使用を制限するための小さな例を次に示します。
new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /de|fr|hu/);moment/locale コンテキストは、/de|fr|hu/ に一致するファイルに限定されます。したがって、これらのロケールのみが含まれます(詳細については、この issue を参照してください)。
new webpack.ContextReplacementPlugin(
resourceRegExp: RegExp,
newContentCallback: (data) => void
);newContentCallback 関数には、ContextModuleFactory の data オブジェクトが渡され、提供されたオブジェクトの request 属性を上書きすることが期待されます。
このコールバックを使用することで、リクエストを新しい場所に動的にリダイレクトできます。
new webpack.ContextReplacementPlugin(/^\.\/locale$/, (context) => {
if (!/\/moment\//.test(context.context)) return;
Object.assign(context, {
regExp: /^\.\/\w+/,
request: '../../locale', // resolved relatively
});
});newContentResource および newContentCreateContextMap パラメータも利用可能です。
new webpack.ContextReplacementPlugin(
resourceRegExp: RegExp,
newContentResource: string,
newContentCreateContextMap: object // mapping runtime-request (userRequest) to compile-time-request (request)
);これらの2つのパラメータを組み合わせて使用することで、よりターゲットを絞った方法でリクエストをリダイレクトできます。newContentCreateContextMap では、ランタイムリクエストをコンパイルリクエストにオブジェクトの形式でマッピングできます。
new ContextReplacementPlugin(/selector/, './folder', {
'./request': './request',
'./other-request': './new-request',
});