webpack IgnorePlugin() on multiple modules

9.4k Views Asked by At

Following the webpack 4.x documentation, we can ignore plugins with IgnorePlugin() method, but the following example only ignore one module (moment/locales)

new webpack.IgnorePlugin({
  resourceRegExp: /^\.\/locale$/,
  contextRegExp: /moment$/
});

If i want to ignore another module (ex : react-tooltip/dist/index.es.js), is there any way to implement another module to ignore, by passing an array with resourceRegExp or contextRegExp for example ?

I tried that :

new webpack.IgnorePlugin(/^\.\/index\.es\.js$/, /react-tooltip\/dist$/),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),

But the file seems to be always present in the bundle

2

There are 2 best solutions below

0
On

You could try matching multiple modules in your regex

new webpack.IgnorePlugin({
  resourceRegExp: /^\.\/(locale|index\.es\.js)$/,
  contextRegExp: /(moment$|react-tooltip\/dist$)/
});

This would match locale and index.es.js within both moment and react-tooltip/dist, which isn't exactly the desired solution but may be good enough.

0
On

You can do it using the filter function option in IgnorePlugin().

This is how you might do it in Webpack 5:

https://webpack.js.org/plugins/ignore-plugin/#using-filter-functions

new webpack.IgnorePlugin({
    checkResource(resource, context) {
        const isLocaleFromMomentImport =
                /^\.\/locale$/.test(resource) && /moment$/.test(context);
        const isReactTooltipIndexFile = /^\.\/index\.es\.js$/.test(resource) && /react-tooltip\/dist$/.test(context);

        return (
           isLocaleFromMomentImport ||
           isReactTooltipIndexFile
        );
    },
}),

Regarding Webpack 4, IgnorePlugin() has also a filter function option, but it's a bit different (checks resource and context separately). If you are still using that version of webpack you should modify the code from above slightly to match your case... although, I can see that this can be a bit tricky because of the separation of checks...