Search code examples
react-leafletleaflet.markercluster

react-leaflet-markercluster export not defined


Uncaught ReferenceError: exports is not defined webpack://project/./node_modules/react-leaflet-markercluster/dist/cjs/index.js?:5 js http://localhost/js/bundle.js:1885

import React from 'react';
import { MapContainer, TileLayer, Marker } from 'react-leaflet'
import MarkerClusterGroup from 'react-leaflet-markercluster'
import 'leaflet/dist/leaflet.css'
import 'react-leaflet-markercluster/styles'

const AppTest = () => {
  return (
    <div className="container">
      <MapContainer className="map-container" center={[49.8397, 24.0297]} zoom={6}>
        <TileLayer
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />        
        <MarkerClusterGroup>
          <Marker position={[49.8397, 24.0297]} />
          <Marker position={[52.2297, 21.0122]} />
          <Marker position={[51.5074, -0.0901]} />
        </MarkerClusterGroup>
      </MapContainer>
    </div>
  )
}

export default AppTest

Using TypeScript and webpack as well as:

  • react 19
  • react-leaflet-markercluster (5.0.0-rc.0) (I tried the previous version too)

before I used a different cluster based on this answer


Solution

  • Cause:

    This caused by using the wrong version of the react-leaflet-markercluster file. In the path of the file where the error occured, you can see that it says cjs. Since you are using import in the exmaple code you provided it needs to use the ejs version, which does exist inside th node_modules react-leaflet-markercluster folder.

    So the issue is mostlikely in your webpack configuration.

    One way to solve this is to add "type": "module" to your package.json.

    Another might be to configure webpack differently:

    resolve: {
     mainFields: ['module', 'main'],
      extensions: ['.js', '.jsx', '.ts', '.tsx'], 
    },
    

    Create custom script:

    I on the other hand had trouble with both, so I decided to manually change the package.json file of the node_module by patching it manually using my own script:

    fix-react-leaflet-markercluster.js

    const fs = require('fs');
    const path = require('path');
    
    const packagePath = path.resolve(__dirname, '../node_modules/react-leaflet-markercluster/package.json');
    const packageJson = require(packagePath);
    
    packageJson.main = './dist/esm/index.js';
    packageJson.exports['.'] = './dist/esm/index.js';
    
    fs.writeFileSync(packagePath, JSON.stringify(packageJson, null, 2));
    console.log('Fixed react-leaflet-markercluster package.json');
    

    Then add this to your package.json scripts:

    "postinstall": "node fix-react-leaflet-markercluster.js"