EricC
EricC

Reputation: 5870

ES6 how to import module "onto" another module

I have already imported a mapboxgl module, then I am trying to import the second "submodule" geocoder like import 'mapbox-gl-geocoder'; and like import mapboxgl.Geocoder from 'mapbox-gl-geocoder';, but that is obviously wrong approach, since I am only getting the error Uncaught ReferenceError: mapboxgl is not defined. How to do this right? Details below...

I am trying to use the Mapbox geocoding example with ES6 (and webpack).

The example uses 2 mapbox js libraries like this (skipping non-interesting part of the file):

<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.16.0/mapbox-gl.js'></script>
<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v1.0.0/mapbox-gl-geocoder.js'></script>
...
<script>
   ...
   var map = new mapboxgl.Map({
      ...
   });

   map.addControl(new mapboxgl.Geocoder());
   ...
</script>
...

So then I want to "translate" this to my project that uses ES6 (and webpack).

When I only use the main mapbox-script (mapbox-gl), I can use that nicely like this:

import mapboxgl from 'mapbox-gl';
let map = new mapboxgl.Map({
    ...
});

But I am getting trouble when I try to include the "submodule" mapbox-gl-geocoder like this (I most probably import the second script the wrong way):

import mapboxgl from 'mapbox-gl';
import 'mapbox-gl-geocoder';
let map = new mapboxgl.Map({
    ...
});
map.addControl(new mapboxgl.Geocoder());

How can I "add" the submodule to the main module? When I try this, I only get the following error:

Uncaught ReferenceError: mapboxgl is not defined

Since it works nicely before I added the two lines 'import 'mapbox-gl-geocoder'; and map.addControl(new mapboxgl.Geocoder()); I am guessing that I am importing incorrectly the second library.

Upvotes: 4

Views: 1593

Answers (1)

Estus Flask
Estus Flask

Reputation: 222369

The second package mapbox-gl-geocoder relies on mapboxgl global, a frequent case of halfhearted CommonJS module support.

Use one of the several ways that Webpack provides to expose mapbox-gl module exports as mapboxgl global variable. The good thing is that mapbox-gl-geocoder expects mapboxgl (not necessarily window.mapboxgl), this means that Webpack can inject mapboxgl local variable, and it will still work as intended.

Or create a helper module to do this independently of bundling environment. Create a file with a name like mapbox-gl-helper.js:

import mapboxgl from 'mapbox-gl';
window.mapboxgl = mapboxgl;
export default mapboxgl;

Then use this it in the file where you need it like this:

import mapboxgl from './mapbox-gl-helper';
import Geocoder from 'mapbox-gl-geocoder';
...

Upvotes: 4

Related Questions