3

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.

ceiphr
  • 33
  • 8

1 Answers1

3

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.

Seth Lutske
  • 9,154
  • 5
  • 29
  • 78
  • I really like the plugin you've recommended. I've implemented it with no luck like this: new webpack.NormalModuleReplacementPlugin( /leaflet\/dist\/leaflet-src\.js$/, "leaflet/dist/leaflet.js" ), – ceiphr May 01 '21 at 01:59
  • I've never personally used that plugin, so I can't help you there. One way or another, you've got to get webpack to forward all references to leaflet to the leaflet/dist/leaflet.js. If you're having trouble with that, it probably deserves its own question. – Seth Lutske May 02 '21 at 04:25
  • That's fair. Thank you for pointing me in the right direction! – ceiphr May 02 '21 at 04:49
  • 1
    I just realized I've been putting my config in the wrong folder. It works flawlessly now! Thanks again! – ceiphr May 02 '21 at 18:01