Mapbox-gl-js: Uncaught ReferenceError: _createClass is not defined (after transpiling with Babel)

Created on 9 Dec 2020  Â·  64Comments  Â·  Source: mapbox/mapbox-gl-js

mapbox-gl-js version: 2.0.0

browser: Google Chrome Version 87.0.4280.67 (Official Build) (x86_64)

Steps to Trigger Behaviour

I'm trying to build a library of Vue components and one component uses mapbox-gl.
I created a test project to showcase the issue.

  1. Create a Vue library (vue create library)
  2. Add mapbox-gl to the library in a component
  3. Build the library
  4. Use the library in a Vue application

When I build and use it I have an error message saying:

Uncaught ReferenceError: _createClass is not defined

Link to Demonstration

https://gitlab.com/antoinealej/test-lib-mapbox-gl-build

Expected Behaviour

Display the map over a beige background

Actual Behaviour

Only displays the beige background container

bug

Most helpful comment

Just making it super concrete for future create-react-users that come across this, a non-eject production build solution is to import mapboxgl like this:

import 'mapbox-gl/dist/mapbox-gl.css';
import mapboxgl from 'mapbox-gl';

// @ts-ignore
// eslint-disable-next-line import/no-webpack-loader-syntax
mapboxgl.workerClass = require('worker-loader!mapbox-gl/dist/mapbox-gl-csp-worker').default;

@arindam1993 @mourner You might consider adding this to the transpilation documentation.

All 64 comments

Thanks for the report! The root cause of this is that after our switch from a ES5 bundle to a ES6 one, Babel transpilation of the bundle breaks it due to the way we set up worker code. We're investigating ways to address this, but the current workaround is to configure your app to exempt mapbox-gl from being transpiled.

Thanks for the explanation!
I'm trying to exclude it from the transpilation, I understand it's more a Babel issue but do you happen to know how I can exclude mapbox-gl in my current situation?
I tried:
vue.config.js

module.exports = {
  css: { extract: false },
  configureWebpack: {
    performance: {
      hints: false,
      maxEntrypointSize: 512000,
      maxAssetSize: 512000
    },
    plugins: []
  },
  chainWebpack: config => {
    config.module
      .rule('js')
      .test(/\.js/)
        .exclude
          .add(/node_modules\/mapbox-gl/)
          .end()
        .use('cache-loader')
          .loader('cache-loader')
          .end()
        .use('babel-loader')
          .loader('babel-loader')
          .end()
  }
}

I just wanted to add that I get the same behavior with an Angular project which of course is also using webpack for transpilation. FWIW I'm also targeting ES6 and that doesn't make a difference.

I don't know if this helps as it is not the direct issue, but its something I found when I was wondering if the problem was my fault:
https://www.javaprogramto.com/2019/12/4-solutions-uncaught-referenceerror-is-not-defined.html

The other issue I noticed in attempting the 2.0.0 version is that I got the error suggesting that AMD or CommonJS scripts cause bailout issues; which in Angular-speak means I had to add it to my allowedCommonJsDependencies entry in the angular.json file.
However, that was NOT true for previous releases.

I'm wondering if there is a CommonJS or other dependency that needs to be loaded and/or checked for being loaded ahead of mapbox-gl functionality being called? Is anything filename dependent? That is when the code gets moved to a shared chunk file with a funky long alphanumeric name. is something looking for mapbox-gl.js and not loading it? These questions are based on a read of the link above.

I also ran across this question on stack overflow and the marked answer is interesting:
https://stackoverflow.com/questions/34973442/how-to-stop-babel-from-transpiling-this-to-undefined-and-inserting-use-str
Given what I said about previous versions not complaining about CommonJS, Might you be compiling what is put up to npm as a commonJS wrapped package without knowing about it based on some babel or other configuration issue on your end?

Admittedly I'm not knowledgeable enough on the setups of everything y'all are using or the consequences of the changing to ES5->ES6, except for what the previous link mentions about different babel versions which wrap scripts in CommJS wrappers.

Hopefully there is something helpful here. If you put up a potential fix I can update my project to use via npm I will be happy to try again and report any findings.

@mourner @arindam1993 I can't manage to make this work without the fix. The map part of my library will be on hold until it's done. Do you guys have an approximate ETA for this?

@antoinealej still investigating this as it's quite a tricky problem, but we expect to have a fix as a part of v2.0.1 in about a week or two, and will also try to find a definite workaround early next week.

I have the same issue after upgrading to 2.0 in an app created with "Create react app". It breaks when loading the map, but it works afterwards while dynamically changing the styles. Rolling back to v1 for the time being.

Same issue here

I have the same issue with React with Create React App. Works great in dev, but does not work with a production build.

Repros with as little as instantiating the map:

const newMap = new mapboxgl.Map({
    container: "map",
    style: 'mapbox://styles/mapbox-map-design/ckhqrf2tz0dt119ny6azh975y',
    center: [-121, -34],
    pitch: 50,
    bearing: 80,
    zoom: 10.0
});

with the following error:

[8c586751-6b29-401a-a42b-d3a9e4cf22ce:1 Uncaught ReferenceError: y is not defined

Same behavior observed in a gatsbyjs app, maps work fine when running gatsby develop, built site throws Uncaught ReferenceError: m is not defined

Heads up that so far we've landed #10219 to make it easier to fix (will be included in the v2.0.1 patch release), and are also adding a docs section on transpilation issues: https://github.com/mapbox/mapbox-gl-js-docs/pull/461

It looks like the fixes will require customizing our bundlers. Is there any fix planned that will help those of us using Create React App with no access to our bundler?

Console Error:-

image

Production Build Screenshot-

image

I pulled my hair for 3 hours to find the issue.

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.

Hello! Are there any workarounds for Create React App integration?
Unfortunately replacing workerClass did not solve the issue.
Thank you

Taking @LeVadim's comment a bit further after reflecting on it a couple of days - I think you all will have a lot of issues filed on you on a constant basis if this doesn't "just work" with create-react-app given its very high level of popularity.

One workaround for Create React App, where the bundler config is not configurable, is to use Webpack's inline loader syntax (after installing the worker-loader package):

// 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.

I tried this an get the same error.

One workaround for Create React App, where the bundler config is not configurable, is to use Webpack's inline loader syntax (after installing the worker-loader package):

// 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.

I tried this an get the same error.

@momolarson this workaround works for me in a React app. I added the worker-loader package (yarn add worker-loader), added the two lines after the imports, and the result of yarn build works fine for me.

@rsippl - wow! thanks for the tip! I had added it before my imports (specifically AFTER the mapbox-gl import). I really appreciate that!

Just making it super concrete for future create-react-users that come across this, a non-eject production build solution is to import mapboxgl like this:

import 'mapbox-gl/dist/mapbox-gl.css';
import mapboxgl from 'mapbox-gl';

// @ts-ignore
// eslint-disable-next-line import/no-webpack-loader-syntax
mapboxgl.workerClass = require('worker-loader!mapbox-gl/dist/mapbox-gl-csp-worker').default;

@arindam1993 @mourner You might consider adding this to the transpilation documentation.

@timfpark yes, this is being added in https://github.com/mapbox/mapbox-gl-js-docs/pull/461

@antoinealej still investigating this as it's quite a tricky problem, but we expect to have a fix as a part of v2.0.1 in about a week or two, and will also try to find a definite workaround early next week.

Hey happy new year! :)
I just upgraded to 2.0.1 and still have the same issue. Was the fix part of 2.0.1 or is it planned to a later release?

@antoinealej with v2.0.1, you'll need to apply one of the workarounds described in https://github.com/mapbox/mapbox-gl-js-docs/pull/461 (soon to be merged into the official docs).

We're working on summarizing the issue, explaining the underlying root cause, why the workarounds are currently necessary, and our next steps in a new ticket in the next few days.

I see there are some React workarounds. Has anyone managed to get it working in Angular? I am seeing similar errors but not sure how to resolve it.

@mourner I believe that the Babel will be able to interpret your package as an ES module if you set the module key in package.json.

See: https://github.com/rollup/rollup/wiki/pkg.module

@nertzy this issue is not about interpreting GL JS as a ES module, it's quite more complicated.

We package code in the bundle in a way that allows sharing a big part of it between the main thread and the worker, significantly reducing bundle size (around 30–40%). When transpilation happens, the runtime helpers such as _createClass are put at the top of the bundle and are not passed to the worker, and there's no easy way to avoid that other than to either transpile everything ourselves (which happened before v2) so that Babel doesn't add anything, but at expense of a bigger bundle size, or drop the current code sharing architecture, increasing the bundle size even more.

We're still looking for a solution that wouldn't involve configuration on user end without compromising performance, but meanwhile, the docs here describe the best approaches for dealing with the problem on the user end.

@mourner Thanks! We were able to get things working by following the advice you linked to.

On our setup (webpacker in a Rails app), we had to tweak what that advice said.

Instead of

    ignore: [ './node_modules/mapbox-gl/mapbox-gl.js' ]

We had to change the filename to be correct for where the mapbox-gl.js file actually is on the filesystem:

    ignore: [ './node_modules/mapbox-gl/dist/mapbox-gl.js' ]

Just wanted to share in case anyone else ran into the same problem we did.

I'm using React V17.0.1 with typescript V^4.0.3 and Mapbox-gl V2.0.1.

After applying the fixes mentioned in the docs I get the following error: Ri.workerClass is not a constructor on build.

Did anyone else get it working in CRA with typescript? Or does anyone know a fix?

Thanks for the report! The root cause of this is that after our switch from a ES5 bundle to a ES6 one, Babel transpilation of the bundle breaks it due to the way we set up worker code. We're investigating ways to address this, but the current workaround is to configure your app to exempt mapbox-gl from being transpiled.

How does one configure the app to exempt mapbox-g ?

@msagerup the docs are at: https://docs.mapbox.com/mapbox-gl-js/api/#forcing-transpilation-with-babel

@msagerup the docs are at: https://docs.mapbox.com/mapbox-gl-js/api/#forcing-transpilation-with-babel

Thanks for your reply. I read that, but I am not using webpack in my project.
I used npx create-react-app.

Maybe a stupid question, but how do i fix it then ?

@msagerup the docs are at: https://docs.mapbox.com/mapbox-gl-js/api/#forcing-transpilation-with-babel

Thanks for your reply. I read that, but I am not using webpack in my project.
I used npx create-react-app.

Maybe a stupid question, but how do i fix it then ?

Create React App uses webpack in the background, so if you run npm run build it is using webpack and babel. If you read the comments starting here, you can see how to solve it (PS - I too am using create-react-app):

https://github.com/mapbox/mapbox-gl-js/issues/10173#issuecomment-753496839

@msagerup the docs are at: https://docs.mapbox.com/mapbox-gl-js/api/#forcing-transpilation-with-babel

Thanks for your reply. I read that, but I am not using webpack in my project.
I used npx create-react-app.
Maybe a stupid question, but how do i fix it then ?

Create React App uses webpack in the background, so if you run npm run build it is using webpack and babel. If you read the comments starting here, you can see how to solve it (PS - I too am using create-react-app):

#10173 (comment)

That worked, thank you :)

So in other words for create-react-app peeps,

change
import mapboxgl from "mapbox-gl";

to

// eslint-disable-next-line import/no-webpack-loader-syntax
import mapboxgl from "!mapbox-gl";

Remember to do it in all places where you import mapbox-gl or your bundle size will go up by about a meg.

Note, this also solved an issue I was having with qr-scanner (https://github.com/nimiq/qr-scanner)

So in other words for create-react-app peeps,

change
import mapboxgl from "mapbox-gl";

to

// eslint-disable-next-line import/no-webpack-loader-syntax
import mapboxgl from "!mapbox-gl";

Remember to do it in all places where you import mapbox-gl or your bundle size will go up by about a meg.

Note, this also solved an issue I was having with qr-scanner (https://github.com/nimiq/qr-scanner)

That did not work for me.

Below is what worked for me :

import ReactMapGL, {Marker} from 'react-map-gl'
import 'mapbox-gl/dist/mapbox-gl.css';
import mapboxgl from 'mapbox-gl';

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

....

Also , remember to npm install worker-loader

HI, i had a similar problem. The main reason I had that bug was MapBox version (2.0.*) a had installed so I install the old verion ("mapbox-gl": "^1.3.1",) and it work perfectly.
PS: My react version "^16.9.0".

Feedback regarding the current transpilation instructions from the perspective of react-map-gl:

While adding additional webpack rules would always work, there are various high-level frameworks that do not allow users to modify the webpack config easily.

Without changing the webpack config, the documentation suggests two options:

  • import mapboxgl from '!mapbox-gl'; - this does not work if mapbox-gl is also imported via a third-party library.
  • Forcing transpilation of the worker - again with third-party library, import mapboxgl from 'mapbox-gl/dist/mapbox-gl-csp'; mapboxgl.workerClass = ... would not work because the library is importing from mapbox-gl. Looks like overriding workerClass on the default export does work, although my understanding is that it's duplicating even more code, defeating the purpose of code sharing even further.

As the maintainer of a third-party library, I do not wish to dictate how users transpile their apps. Hardcoding either of the above solutions into the wrapper is problematic because it will force certain bundler/dev dependency set up onto the end user.

Considering the amount of friction this has generated, I don't think it's unreasonable to distribute a fully transpiled version of mapbox-gl that is on par with v1. I suggest that mapbox-gl add a module field to package.json that points to the ES6 build, and then point main to a ES5 build instead. I believe both webpack and rollup respect module over main. This will allow third-party libraries to choose the entry point that makes the most sense.

using the worker loader or webpack did not work in my case.

I assume it's related to what @Pessimistress mentioned. I use create-react-app with react-mapbox-gl which is also importing mabox-gl. So even if I override my import of mapbox-gl I still get the same error.

ReferenceError: y is not defined

For now it seems like I am forced to downgrade to 1.x

I think this needs a solution rather than just a "workaround".

same behavior using v2.1.1 with react-map-gl v6.1.8

  • map in dev
  • no map in prod and
    ReferenceError: g is not defined

timfpark solution of Jan 3rd worked

Another possible way , instead of using the ! syntax is modifying the browserslist spec in package.json. In my testing modifying the one created by create-react-app slightly, works.

browserslist: [
      ">0.2%",
      "not ie 11",
      "not dead",
      "not chrome 49"
    ]

@Pessimistress I don't think supplying two builds with module and main will work in this case. module only specifies that the module resolver should use ES6 module syntax (import/export) instead of require for resolving dependencies, it will not inform transpilers on how to transpile the package for specific language features (like classes, arrow functions etc).

Our goal with this change was to provide a modern bundle that works with almost all modern browsers, but with an escape hatch of workerClass if someone needs to transpile it for older browsers. With that in mind would a recommended browserlists spec, like the one above be considered a valid solution?

@arindam1993 Supplying two builds is not going to solve the issue on its own. In the react-map-gl case, the library is distributed with an ES5 build, an ESM build and an ES6 build. We can direct the ES5 and ESM builds to import from the fully transpiled mapbox-gl version, and the ES6 build to import from the ES6 mapbox-gl version.

@Pessimistress the workerClass hook should be usable to achieve exactly that. Instead of having to point to different bundles it should allow clean transpilation irrespective of target.

I'm happy to work on a change upstream into react-map-gl and started here https://github.com/visgl/react-map-gl/pull/1365

Would appreciate any input and best ways to test the various bundles.

Is there any official fix in sight? This issue is pretty severe

Is there any official fix in sight? This issue is pretty severe

Just downgrade react-map-gl to version 5.3.4. It's work for me.

I didn't try to update mapbox-gl to version 2.0
I use version 2.1.1 of mapbox-gl.

I don't know why it's work for me but it does

any update to this?
using a third party library and the solutions posted do not help.....

react-mapbox-gl if anyone has fixed it using this library wtih CRA and typescript

@solarstar101 what solutions haven't worked? I'm using @zacharyliu's fix with CRA and it works:

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

I added this in the very root of my app- one of the first files that loads.

This required adding the extra NPM package:

"worker-loader": "3.0.8"

EDIT: Just re-read your comment @solarstar101 and realized I misread react-map-gl rather than what you really meant which is react-mapbox-gl. It's unclear to me if this will solve the issue for you, but I'll keep my response here in case it's helpful for you or anyone else

@solarstar101, my environment is working with CRA, typescript, and react-map-gl. I'm using StaticMap from react-map-gl and similar to what everyone else has suggested my solution is below:

import mapboxgl from "mapbox-gl";
import { StaticMap } from "react-map-gl";
...
// @ts-ignore
// eslint-disable-next-line import/no-webpack-loader-syntax, import/no-unresolved
mapboxgl.workerClass = require("worker-loader!mapbox-gl/dist/mapbox-gl-csp-worker").default;

Even though mapboxgl isn't something you work with directly, it is a dependency of react-map-gl.

Relevant module versions from package.json:

"react": "17.0.1",
"react-map-gl": "^6.1.7",
"worker-loader": "^3.0.8"

I hope this helps.

I was just experiencing this issue on my Gatsby v3 + TS project. Worked locally, failed on CI (Netlify in our case).
@bmg817 's solution fixed it! Thank you!
It'd also be great to know when we can remove this workaround. It's a pretty major issue.

After a bunch of digging into various options, including providing a ES5 build here

It seems all it serves to do is revive an old error https://github.com/mapbox/mapbox-gl-js/issues/3422, most create-react-app users never saw this error because it has an explicit exclusion in its Babel presets for that particular transform. https://github.com/facebook/create-react-app/blob/3c02ca74f9eb099e4d5eed3f646bfad118da635b/packages/babel-preset-react-app/create.js#L87

So I think the easiest, also most performant solution for create-react-app users would be to update browserlists in package.json to exclude older browsers

browserslist: [
      ">0.2%",
      "not ie 11",
      "not dead",
      "not chrome 49"
    ]

And if you really need transpilation for your project to force support for IE11 and old versions of chrome then the using the workerClass hook as @bmg817 pointed out is the way to go.

It seems all it serves to do is revive an old error #3422

Just providing one data point, prior to v2 react-map-gl has never got any bug reports regarding transpilation. Right now it's at least twice a week, with the main issue pinned.

If we look at the most popular React frameworks that hide the transipilation configs:

You can exclude mapbox-gl from being transpiled with CRACO. It works with react-mapbox-gl + react + TS.

craco.config.js

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

Source: https://docs.mapbox.com/mapbox-gl-js/api/#transpiling-v2

@Pessimistress even if we were to provide an ES5 bundle wouldn't there be some implementation work in react-map-gl to redirect the imports to the appropriate bundle based on build target. In that case can the import be redirected to use the mapboxgl.workerClass hook for ES5 builds?

The reason I'm pushing back against this is because with v2, GL-JS is only intended to be used with modern browsers( hence the dropping of IE11 support). So supplying an ES5 bundle just for the sake of bundler and build system compatibility instead of functionality seems very redundant.

@arindam1993

can the import be redirected to use the mapboxgl.workerClass hook for ES5 builds?

A key difference between react-map-gl and mapbox-gl is that it does not distribute its own pre-built bundle. Anyone using the wrapper can choose to use it with any compatible mapbox-gl version. By hard-coding the workerClass hook, every user will be required to install worker-loader to be able to build their apps at all. How does that make the current situation better?

Of course, a few extra hoops would be required for anyone who wants transpilation, but most people shouldn't (for performance reasons) and probably don't need to transpile down all the way to support IE11/chrome 49. JS and WebGL performance on those older browsers is unacceptable anyways.

Most users should be able to go in this order:

  1. Update browserlist in package.json to modern-ish levels (perf boost, smaller bundle sizes and faster load times as a bonus)
  2. If 1 doesnt work bcoz some legacy sections of the app or certain dependencies need ES5 transpilation, explicit exclusions can be configured via CRACO or webpack.config.js
  3. If 2. doesnt work bcoz the user really needs a dynamic WebGL map to work in IE11 class browsers then they can setup the workerClass hook to allow for transpilation.

Intuitively 1. should be the largest chunk of users, 2 covers few more users with older projects that may have legacy chunks, and 3 should be the smallest minority.

Again I want to reiterate that the reason I'm pushing back is that while an ES5 bundle would provide compatibility with current default bundler configs, it comes at the cost of performance, longer load times and larger bundle sizes. Most users don't need to pay those costs since they aren't really targeting those environments.

So in other words for create-react-app peeps,
change
import mapboxgl from "mapbox-gl";
to
// eslint-disable-next-line import/no-webpack-loader-syntax
import mapboxgl from "!mapbox-gl";
Remember to do it in all places where you import mapbox-gl or your bundle size will go up by about a meg.
Note, this also solved an issue I was having with qr-scanner (https://github.com/nimiq/qr-scanner)

That did not work for me.

Below is what worked for me :

import ReactMapGL, {Marker} from 'react-map-gl'
import 'mapbox-gl/dist/mapbox-gl.css';
import mapboxgl from 'mapbox-gl';

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

....

Also , remember to npm install worker-loader

This worked for me.
USING the newest versions of react-map-gl && mapbox-gl.
I must mention this worked for a production build on AWS Amplify.

None of the above solutions are working when the app runs locally!

I’m using react-map-gl in Fuse.js (wrapper based on CRA) and we want to include three different map styles. If the map style is set to _satellite_ then it gets rendered properly otherwise in any other style like _light_, _landscape_, etc. only the background color of the map is shown and I get Uncaught ReferenceError: _createClass is not defined error in console.

I get this error when I run the app locally. The solutions given here are for production builds but I still tried them all. However, nothing worked for me. I tried @arindam1993's solution, @mtuanp's solution and @belferink1996's solution. Can someone please guide me?

I’m using Mac OS v10.15.7 and relevant package versions are:
react-map-gl: 6.1.10
mapbox-gl: 1.8.1
node: >=10.19.0

image

@dhruv10 it looks like you tried a subset of solutions from the ones you've listed. Try this one (which is just a variation of this solution by @zacharyliu). See if it works for you.

Hi @dhruv10,
Have tried downgrade react-map-gl to the latest 5 version https://github.com/visgl/react-map-gl/releases/tag/v5.3.10.
Because the version 6 is only supported with mapbox-gl >=2, as I know.

Aha, the main issue was the version incompatibility between react-map-gl and mapbox-gl as pointed out by @mtuanp in

Hi @dhruv10,
Have tried downgrade react-map-gl to the latest 5 version https://github.com/visgl/react-map-gl/releases/tag/v5.3.10.
Because the version 6 is only supported with mapbox-gl >=2, as I know.

After doing this, both the solutions (given by @bmg817 and @arindam1993) were working. I even tried after upgrading both dependencies to the latest version. Finally, this is what I'm using now:

"react-map-gl": "6.1.10"
"mapbox-gl": "2.1.1"
"node": ">=10.19.0"

Thank you all :)

After a bunch of digging into various options, including providing a ES5 build here

It seems all it serves to do is revive an old error #3422, most create-react-app users never saw this error because it has an explicit exclusion in its Babel presets for that particular transform. https://github.com/facebook/create-react-app/blob/3c02ca74f9eb099e4d5eed3f646bfad118da635b/packages/babel-preset-react-app/create.js#L87

So I think the easiest, also most performant solution for create-react-app users would be to update browserlists in package.json to exclude older browsers

browserslist: [
      ">0.2%",
      "not ie 11",
      "not dead",
      "not chrome 49"
    ]

And if you really need transpilation for your project to force support for IE11 and old versions of chrome then the using the workerClass hook as @bmg817 pointed out is the way to go.

this one is sadly not working for me. not sure why tho.
Im using CRA and just the vanilla mapbox-gl not the react wrapper,

any idea where the problem could be? my application seems to be the same after chaning the browserslist but the map still dosent work. is there anything else i would've to do for this to work?

the other 2 solutions worked for me. but i wouldnt mind cleaner fix

Hi everyone,
After I ran into this issue a couple of months ago, we've decided to keep mapbox-gl at 1.13.0 for now (this worked fine, except tests).
I've been trying for a couple of hours now to get it working (build without reference-error and working tests), but haven't been able to.
Our problem is that when we are able to build the tests are complaining about the workaround > "Cannot find module worker-loader!..." and when we comment this out, we get the map.on is not a function. (Yes, we've tried this fix).

So I'm wondering if the Mapbox team has an idea how to solve these issues, but even more, I'm curious to whether there will be an actual fix that's not a workaround?

If anyone got mapbox' latest version working combined with CRA, without rewired, meaning that both build and testing succeeds I would be very interested in an example repo they might want to share?

Please let me know as I'm very curious what I'm doing wrong!

You can exclude mapbox-gl from being transpiled with CRACO. It works with react-mapbox-gl + react + TS.

craco.config.js

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

Source: https://docs.mapbox.com/mapbox-gl-js/api/#transpiling-v2

I have Rails 6 + webpack + mapbox-gl. I had same issue and simple code solution from docs helped to exclude the lib.

import mapboxgl from '!mapbox-gl';

@IvanDreamer Thanks, this is the easier solution if you're working with Weback.
https://docs.mapbox.com/mapbox-gl-js/api/#transpiling-v2

The browserslist approach works well for me in create-react-app with some tweaks.

  1. Add these two lines to the browserslist section in package.json:
"browserslist": {
  "production": [
    ">0.2%",
    "not dead",
    "not op_mini all",
+   "not chrome < 51",
+   "not safari < 10"
  ],
  "development": [
    "last 1 chrome version",
    "last 1 firefox version",
    "last 1 safari version"
  ]
}
}

(The full section might look different depending on your config and create-react-app version.)

  1. rm -rf node_modules/.cache to clear the Babel cache (mentioned in https://create-react-app.dev/docs/supported-browsers-features/)

According to caniuse, Chrome 51 and Safari 10 were the first versions of those browsers to have full ES6 support. Different versions of the caniuse-lite db include different versions of these browsers as having >0.2% usage, which is why https://github.com/mapbox/mapbox-gl-js/issues/10173#issuecomment-793179698 may not always work. This config should cover all the cases.

Was this page helpful?
0 / 5 - 0 ratings