webpackmapbox-glmapbox-gl-draw

Using mapbox-gl and @mapbox/mapbox-gl-draw with webpack


I have trouble including mapbox-gl and @mapbox/mapbox-gl-draw in a webpack bundled app. I found that mapbox should be included with the dist version, so I required like that: require('mapbox-gl/dist/mapbox-gl.js') (same for Draw), and it works fine in dev, but crash at runtime on production build, we get errors such as e is not defined

Is there any config needed ?


Solution

  • Ok, I found out the solution, posted on diverse issues. First of all, we can use the regular require of mapbox and mapbox-gl for simplicity using :

    const mapboxgl = require('mapbox-gl');
    const MapboxDraw = require('@mapbox/mapbox-gl-draw');
    

    We just need to specify to webpack that those actually point to their build version, so we add an alias :

    resolve: {
        ...
        alias: {
          'mapbox-gl': 'mapbox-gl/dist/mapbox-gl.js',
          '@mapbox/mapbox-gl-draw': '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.js',
        }
      }
    

    But the error at runtime was caused by the fact that I use Uglify in my webpack config. So the mapbox package, already minified as we use the dist version, was put again through uglify. To avoid that, we need to tell webpack to not process mapbox package, so we had the following rule in the webpack config :

    module: {
        ...
        noParse: /(mapbox-gl)\.js$/
    }