Fabian Svensson
Fabian Svensson

Reputation: 169

Mapbox-gl-geocoder in Next.JS - TypeError: EventEmitter is not a constructor

I have been using Mapbox-GL and mapbox-gl-geocoder in a Next.JS version 13 project and they have worked fine up until now. I noticed when accessing the map that I get this error:

EventEmitter is not a constructor at new MapboxGeocoder (webpack-internal:///./node_modules/@mapbox/mapbox-gl-geocoder/lib/index.js:87:24)

enter image description here

My code (omitting unrelated parts) is just this:

import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import MapboxGeocoder from '@mapbox/mapbox-gl-geocoder';
import '@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css';

const geocoder = new MapboxGeocoder({
    accessToken: mapboxgl.accessToken,
    marker: false,
    flyTo: false,
    mapboxgl: mapboxgl
});

map.current.addControl(geocoder);

The error occurs directly at the MapboxGeocoder constructor new MapboxGeocoder

I have found that others using Vue 3 and vite have had the same issue: TypeError: EventEmitter is not a constructor at new MapboxGeocoder

I have tried importing Events together with MapboxGeocoder directly inside my Map Component:

import EventEmitter from 'events';

But this does not work. I am using the updated versions and the versions have not changed since last time this worked (about a week or two ago): "@mapbox/mapbox-gl-geocoder": "^5.0.1", "@types/mapbox-gl": "^2.7.10", "mapbox-gl": "^2.13.0", "@types/mapbox__mapbox-gl-geocoder": "^4.7.3",

Any idea how to solve this? Thank you in advance :)

Upvotes: 0

Views: 615

Answers (1)

Fabian Svensson
Fabian Svensson

Reputation: 169

I ended up creating a new project from scratch and added mapbox-gl as well as Geocoder to it. Everything worked, using the exact same versions as those I have in my original project. Therefore, it look like a dependency issue in the package.json or configuration.

I eventually managed to figure it out. My colleague had updated the package.json file and added ./lib to the NODE_PATH variable:

NODE_PATH=./node_modules:./lib next dev -p 8090

It seems that the Geocoder library has some incompatibility with the lib path. I haven't investigated why, but removing or changing this path solves the issue.

So if you have the same problem it is likely a configuration issue.

Upvotes: 0

Related Questions