ContextReplacementPlugin

2023-06-01 15:31 更新

Context 是指带有诸如 ​require('./locale/' + name + '.json')​ 之类的表达式的要求。当遇到这样的表达式时,webpack 会推断目录 ​('./locale/')​ 和正则表达式 ​(/^.*\.json$/)​。由于在编译时不知道名称,webpack 将每个文件作为模块包含在包中。

ContextReplacementPlugin​ 允许您覆盖推断的信息。有多种方法可以配置插件:

Usage

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​ context 仅限于匹配 ​/de|fr|hu/​ 的文件。因此,仅包括那些语言环境。

Content Callback

new webpack.ContextReplacementPlugin(
  resourceRegExp: RegExp,
  newContentCallback: (data) => void
);

newContentCallback​ 函数被赋予了 ​ContextModuleFactory​ 的数据对象,并有望覆盖所提供对象的 ​request​ 属性。

使用此回调,我们可以将请求动态重定向到新位置:

new webpack.ContextReplacementPlugin(/^\.\/locale$/, (context) => {
  if (!/\/moment\//.test(context.context)) return;

  Object.assign(context, {
    regExp: /^\.\/\w+/,
    request: '../../locale', // resolved relatively
  });
});

Other Options

newContentResource​ 和 ​newContentCreateContextMap​ 参数也可用:

new webpack.ContextReplacementPlugin(
  resourceRegExp: RegExp,
  newContentResource: string,
  newContentCreateContextMap: object // mapping runtime-request (userRequest) to compile-time-request (request)
);

这两个参数可以一起使用,以更有针对性的方式重定向请求。 ​newContentCreateContextMap​ 允许您以对象的形式将运行时请求映射到编译请求:

new ContextReplacementPlugin(/selector/, './folder', {
  './request': './request',
  './other-request': './new-request',
});

Further Reading


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号