Search code examples
javascriptcordovabrowserifymapbox-gl-js

mapbox-gl-js won't render when bundled with browserify


I have an odd issue with mapbox-gl-js. When I add the mapbox-gl.js file as CDN to html doc head, the map renders fine. When I require it and bundle it with browserify as documented, the map doesn't render and I get a bundling error like this: Error: Cannot find module './feature' from '/home/.../mbtst/node_modules/mapbox-gl/dist'

The docs describe how to use a module bundler: https://www.mapbox.com/mapbox-gl-js/api/. At the time of posting this issue that was (it has since been changed due to this issue):

npm install --save mapbox-gl
import mapboxgl from 'mapbox-gl/dist/mapbox-gl';
// or "const mapboxgl = require('mapbox-gl/dist/mapbox-gl');"

My map is initiated like this:

mapboxgl.accessToken = 'pk.eyJ1IjoiZWxsdnRyemVnIiwiYSI6ImNpejl4M2M0NDAxbWoycXRlanZnc283dnYifQ.sPFCSTsdlCOp1hk6afDvJg';
this.map = new mapboxgl.Map({
    container: 'map-container', // container id
    style: 'mapbox://styles/mapbox/streets-v9', 
    center: [6.16342, 62.47126], // aalesund 
    zoom: 11
});

If I just require the module as such require('mapbox-gl'); - same error.

I even tried to save the file from the CDN source and require that file - which complains about multiple dependency modules missing.

The code is in this repo: https://github.com/awesomemaptools/mbtst

PS: I need to bundle the script for offline use in a Cordova app, ie using cdn is not an option.


Solution

  • It turns out that it is a bug and the folks at mapbox are working to fix it, see issue here: https://github.com/mapbox/mapbox-gl-js/issues/4453

    Meanwhile I upgraded from mapbox-gl version "^0.33.1" to "^0.34.0" and now it works with a workaround when including src instead of dist like this:

    const mapboxgl = require('mapbox-gl/src/index.js');
    

    I tried that with the previous version but it didn't work then.