简体   繁体   中英

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.

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.

The code you provided seems basically OK. Try to use require instead of import :

const mapboxgl = require('mapbox-gl/dist/mapbox-gl');

Then call the following in the terminal:

browserify your-main-js-file.js > bundle.js

This adds your code and the required modules to the created JavaScript file bundle.js , so everything should be available even if your're offline.

Afterwards add the output bundle to your HTML page via script-tag:

<script src="bundle.js"></script>

See https://github.com/substack/browserify-handbook#bundling-for-the-browser for a bit more details and check the options browserify takes to customize your bundle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM