How do I reduce the bundle size of React Leaflet?

Viewed 543

I have a Gatsby.js project where the parsed size of my bundle is 3.92 MB. 1.1 MB of that is leaflet-src.js. Leaflet also seems to supply leaflet.js which is only 508 KB. After reading this issue, whenever I import Leaflet, I always import this smaller version, like so:

import L from "leaflet/dist/leaflet"

Regardless, whenever I run Webpack Bundle Analyzer, both leaflet-src.js and leaflet.js are imported: Webpack Bundle Analyzer Result

It seems like the GitHub issue I mentioned was hinting at configuring webpack to use the optimized version, but I'm really struggling to figure out how to do that exactly.

Any help would be very much appreciated.

1 Answers

So this may be an issue of how react-leaflet is importing leaflet. While any direct references from your code to leaflet may use the import L from "leaflet/dist/leaflet" option, react-leaflet source and build code simply imports from 'leaflet', with the assumption that you have leaflet as a peer dependency. So that means react-leaflet is bringing in the unminified version, as mentioned here.

As react-leaflet author LeCam states, you've got to manage this yourself. You'll have to find a way to tell webpack to replace all references to the 'leaflet' module with directions to the 'leaflet/dist/leaflet' file. You can start by looking at the redirect an import issue with webpack, or the NormalModuleReplacement plugin.

Also, this should help in your own code, as you can just import L from 'leaflet', and if you've setup your webpack correctly, it will redirect to the minified version.

Related