how do you import mapbox-gl-draw using webpack?

1.8k views Asked by At

I am using create-react-app and trying to install mapbox-gl-draw.

npm install @mapbox/mapbox-gl-draw

This works with some npm warnings. I then try to pull mapbox-gl-draw into a component like this:

import React,{Component} from 'react';
import mapboxgl from 'mapbox-gl/dist/mapbox-gl.js';
import ReactMapboxGl from 'react-mapbox-gl';
import MapboxDraw from '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw'

console.log(MapboxDraw)

I just get an empty object.

I am using create-react-app. Do I need to use a different webpack .config file.

What is the best way to import mapbox modules like this?

2

There are 2 answers

1
medv On BEST ANSWER

If you're using webpack, you need to alias to use mapbox-gl dist file, here is how I have done it using webpack2:

    resolve: {
      modules: ['src', 'node_modules'],
      extensions: ['.js', '.jsx', '.json', '.css', '.svg'],
      alias: {
        // mapbox-gl related packages in webpack should use dist instead of the default src
        '@mapbox/mapbox-gl-draw': path.resolve(root, 'node_modules/@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.js'),
      },
    },

Variable "root" was defined earlier in the file to refer to the root directory of the project, on the same level as package.json etc.

The same problem can happen in react-map-gl-alt where you need to alias 'mapbox' to 'node_modules/mapbox/dist/distfilehere.js'.

0
Shawn Goulet On

To expand upon medv's answer, at current, in your package.json, you need to add the mapbox-gl v0.270 - v0.38.0, like:

"mapbox-gl": ">=0.27.0 <=0.38.0 when using "@mapbox/mapbox-gl-draw": "^1.0.1".

This is explained at the 'Requires' line here & if you look at the peerDependencies in the package.json.