Skip to content

Instantly share code, notes, and snippets.

@nnennajohn
Forked from iamakulov/index.md
Created June 27, 2019 17:40
Show Gist options
  • Save nnennajohn/d1cd32d27adcdc1d6b662d2cf4a24116 to your computer and use it in GitHub Desktop.
Save nnennajohn/d1cd32d27adcdc1d6b662d2cf4a24116 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