javascriptleafletverceles6-modules

Uncaught ReferenceError: require is not defined, in my Vercel app


Problem

I have a React app using Leaflet.js (v.1.9.0) and I host it in Vercel. Building works OK, but when visiting my app online logs this message in console:

Uncaught ReferenceError: require is not defined.

Where it happens

The file & line happening is ...assets/index-BKsOcw9k.js:67 where index-BKsOcw9k.js is a build file inside the dist/ folder. Locating it the code, it has this: ...QT.exports=e(require("leaflet"));e... and the problem is in the require.

My search

Searching around and asking AI, I understand that there is a problem with ESM and Leaflet (maybe, Rollup is included in the problem). I thought upgrading to Leaflet v.2 where it says it has Fully ESM support and that may solve the problem but there are conflicts with other packages (e.g. leaflet-draw, leaflet-geoman, etc...).

I import leaflet in my main component like that: import L from "leaflet";. I've also tried import * as L from "leaflet";. None of them working when re-deploying in Vercel.

Thanks in advance!


Solution

  • Found out that the problem was in the leaflet-iconex plugin I use (as a file, not through NPM).

    Its UMD wrapper "caused" the problem when checking for CommonJS module. The bundler was keeping the require() part:

    } else if (typeof exports === "object") {
        // CommonJS module
        module.exports = factory(require("leaflet"));
    } else ...
    

    as it is, thus breaking.

    Fixed it by just commenting out the code block.