Skip to content

Instantly share code, notes, and snippets.

@trkhanh
Forked from iamakulov/index.md
Created July 9, 2020 10:25
Show Gist options
  • Select an option

  • Save trkhanh/2549c41a3a05b8b59de5972be14cc6ca to your computer and use it in GitHub Desktop.

Select an option

Save trkhanh/2549c41a3a05b8b59de5972be14cc6ca to your computer and use it in GitHub Desktop.
Webpack’s ContextReplacementPlugin examples

Webpack’s ContextReplacementPlugin examples

This is an example to my article “How webpack’s ContextReplacementPlugin works”

You have the moment.js library, and you have a dynamic import:

require('./locale/' + name + '.js')

Single parameter: directory

new ContextReplacementPlugin(
  /moment[\/\\]locale/,
  path.resolve(__dirname, './src/locales'),
)

This plugin instance will match all dynamic imports that reference the /moment[\/\\]locale/ directory.

It will change the directory in which webpack should look for the files to ./src/locales – instead of something like ./node_modules/moment/locales. Webpack will still look into subdirectories and still match the files against /^.*\.js/ regular expression.

Single parameter: recursive flag

new ContextReplacementPlugin(
  /moment[\/\\]locale/,
  false,
)

This plugin instance will match all dynamic imports that reference the /moment[\/\\]locale/ directory.

It will make webpack not look in the subdirectories of the root directory. Webpack will still look into the root ./locales directory and still match the files against /^.*\.js/ regular expression.

Single parameter: files regular expression

new ContextReplacementPlugin(
  /moment[\/\\]locale/,
  /(en-gb|ru)\.js/,
)

This plugin instance will match all dynamic imports that reference the /moment[\/\\]locale/ directory.

It will make webpack match the files against the /(en-gb|ru)\.js/ regular expression – instead of /^.*\.js/. Webpack will still look into the root ./locales directory and still recursively traverse its subdirectories.

Multiple parameters

new ContextReplacementPlugin(
  /moment[\/\\]locale/,
  path.resolve(__dirname, './src/locales'),
  /(en-gb|ru)\.js/,
)

This plugin instance will match all dynamic imports that reference the /moment[\/\\]locale/ directory.

It will change the directory in which webpack should look for the files to ./src/locales – instead of something like ./node_modules/moment/locales. Also, it will make webpack match the files against the /(en-gb|ru)\.js/ regular expression – instead of /^.*\.js/. Webpack will still look into subdirectories.

Follow me on Twitter: @iamakulov

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment