Hiding Critical Dependency Warnings from webpack
How to acknowledge warnings raised by webpack when you know they’re safe.
Yesterday I encountered a warning in webpack. We had introduced our templating library to the frontend, and now when building we would see the message:
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
Webpack bundles together all the code and libraries that make your application. To make the smallest bundle it attempts to “understand” which bits of libraries you are using. This means that it can save space by only bundling execution paths that your code could take. For example, if you bundled the AWS-SDK it might only bundle the code for the services you’ve used.
The warning means that part of my (or in this case, a library author’s) code imports modules in such a way that webpack cannot reliably determine what code is used and which bits can be ignored.
In our case it was the following lines of code:
By inspecting the code we can see that the lazy-cache
modified require function has the same behaviour as node’s standard require
. This means that Webpack’s static analyser will work fine here and the warning can safely be ignored.
To acknowledge the warning we can use the ContextReplacementPlugin
bundled with webpack. This allows use to ‘acknowledge’ the warning message by deleting it:
Of course, like all warnings, it’s up to you to document why you felt this warning could be safely acknowledged.
The lesson: You can use the Webpack’s ContextReplacementPlugin
to acknowledge dependency warnings that you have investigated and found safe.