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
This comment has been minimized.
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?