Skip to content

Instantly share code, notes, and snippets.

@iamakulov
Last active September 3, 2020 04:31
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save iamakulov/59d88d00404259abb83daaf51b70cb07 to your computer and use it in GitHub Desktop.
Save iamakulov/59d88d00404259abb83daaf51b70cb07 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

@frankandrobot
Copy link

What do you mean by "match all dynamic imports"? In concrete terms, what would be the difference between not using this plugin and using the given config?

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