I have a legacy react app that I'd like to optimize in terms of the bundle size. There are a few dependencies that I'm using that include a pdfjs-dist library.
I can decide not to use the functionality that requires me to include that library. Is there a way I can ignore bundling of this dependency to slim down on the bundle size?
So far I've tried using externals, but this didn't work. I can still see the package in webpack-bundle-analyzer.
externals: {
"pdfjs-dist": '',
},
The bundler is supposed to bundle all the dependencies. You cannot simply ask it to ignore a certain dependency.
But in your case, if you are not going to execute the code that depends on the pdfjs-dist
module, then you can use external to fake the dependency. You can simply say:
externals: { 'pdfjs-dist': 'X' }
Here, the Webpack will assume that there is a global variable named X
accessible as globalThis.X
or window.X
, etc. Webpack will link all the invocation of pdfjs-dist
to this global X
variable. Point here is that your external configuration cannot have a blank string. So, as long as you not calling X
, your code would safely work.
Further, to create a fake X
so that when any property or method is called accidentally, instead of error, you can make it fail silently using ES Proxy interceptor. Add this somewhere in your initialization sequence as:
const handler = {
get: function(obj, prop) {
return 0;
}
};
// Set as a global object using globalThis or window.
window.X = new Proxy({}, handler);