3

Only in production using vercel my Mapbox map doesn't work.

This is the error message I get, which links to the mapbox documentation:

An error occurred while parsing the WebWorker bundle. This is most likely due to improper transpilation by Babel; please see https://docs.mapbox.com/mapbox-gl-js/guides/install/#transpiling

On the official documentation it says we should select a set of compatible transforms.

0.2%, not dead, not ie 11, not chrome < 51, not safari < 10

Which I did, but this did not work:

package.json

"production": [
      ">0.2%",
      "not dead",
      "not ie 11",
      "not chrome < 51",
      "not safari < 10",
      "not op_mini all"
],

We can as well use import mapboxgl from '!mapbox-gl'; to exclude GL JS explicitly from transpilation. Which also gives me an error message.

Or we can configure this centrally in webpack.config.js which is not accessible using react-create-app.

Since I do not want to use react-scripts eject I installed react-app-rewired following this StackOverflow post

My configuration looks like this:

module.exports = {
    use: {
        loader: 'babel-loader',
        options: {
            ignore: ['./node_modules/mapbox-gl/dist/mapbox-gl.js']
        }
    }
}

But that doesn't work either.

Does someone know a sure way to fix this mapbox error? Or is what I have already tried wrong somehow?

GitHub issue

crg
  • 4,284
  • 2
  • 29
  • 57

1 Answers1

2

I've found an answer searching deeper on the GitHub issue which worked.

zacharyliu commented on 23 Dec 2020

One workaround for Create React App, where the bundler config is not configurable, is to use Webpack's inline loader syntax.

First, install the worker-loader package (yarn add worker-loader). Then add the following snippet somewhere in your app, ideally right below your imports:

// eslint-disable-next-line import/no-webpack-loader-syntax
mapboxgl.workerClass =
require('worker-loader!mapbox-gl/dist/mapbox-gl-csp-worker').default;
You probably need the eslint-disable line so Create React App doesn't
error out the build.

Since I do not use yarn I did

npm install worker-loader --save-dev

Then on my js file

import mapboxgl from 'mapbox-gl';
mapboxgl.workerClass = require('worker-loader!mapbox-gl/dist/mapbox-gl-csp-worker').default; // eslint-disable-line

The // eslint-disable-line comment disables the linter rule for just that line.

crg
  • 4,284
  • 2
  • 29
  • 57
  • Thank you! I had the exact same problem and this solved it for me as well. I have the feeling that overwriting webworker configs as outlined on the Mapbox help page doesn't work anymore with newer webworker versions because loader options are set differently.. – denise Sep 01 '22 at 14:11