mapbox / mapbox-gl-js

Interactive, thoroughly customizable maps in the browser, powered by vector tiles and WebGL
https://docs.mapbox.com/mapbox-gl-js/
Other
11.01k stars 2.2k forks source link

Uncaught ReferenceError: _createClass is not defined (after transpiling with Babel) #10173

Closed antoinealej closed 3 years ago

antoinealej commented 3 years ago

--- πŸ”΄ EDIT from a gl-js maintainer πŸ”΄ ---- We've just opened #10565 do go over some of the decisions of why we moved to ES6, and also summarizing the solutions that everyone has contributed in this thread. Would love for the discussion to be continued there. πŸ™‡πŸ½ --- πŸ”΄ END EDITπŸ”΄-----

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

mourner commented 3 years ago

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.

antoinealej commented 3 years ago

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()
  }
}
arthur-clifford commented 3 years ago

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.

antoinealej commented 3 years ago

@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?

mourner commented 3 years ago

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

LeonSkrilec commented 3 years ago

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.

mkmdivy commented 3 years ago

Same issue here

timfpark commented 3 years ago

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
chriswhong commented 3 years ago

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

mourner commented 3 years ago

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

dfalling commented 3 years ago

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?

dhruv9499 commented 3 years ago

Console Error:-

image

Production Build Screenshot-

image

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

zacharyliu commented 3 years ago

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.

LeVadim commented 3 years ago

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

timfpark commented 3 years ago

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.

momolarson commented 3 years ago

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.

rsippl commented 3 years ago

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.

momolarson commented 3 years ago

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

timfpark commented 3 years ago

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.

mourner commented 3 years ago

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

antoinealej commented 3 years ago

@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?

mourner commented 3 years ago

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

joedjc commented 3 years ago

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.

nertzy commented 3 years ago

@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

mourner commented 3 years ago

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

nertzy commented 3 years ago

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

brdv commented 3 years ago

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?

msagerup commented 3 years ago

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 ?

asheemmamoowala commented 3 years ago

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

msagerup commented 3 years ago

@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 ?

momolarson commented 3 years ago

@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 commented 3 years ago

@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 :)

MatthewPosgate commented 3 years ago

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)

msagerup commented 3 years ago

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

kcfurtado commented 3 years ago

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

Pessimistress commented 3 years ago

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:

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.

MarkLyck commented 3 years ago

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

raphaelfavier commented 3 years ago

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

timfpark solution of Jan 3rd worked

arindam1993 commented 3 years ago

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?

Pessimistress commented 3 years ago

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

arindam1993 commented 3 years ago

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

vandres commented 3 years ago

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

yeldev commented 3 years ago

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.

yeldev commented 3 years ago

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

solarstar101 commented 3 years ago

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

dfalling commented 3 years ago

@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"
bmg817 commented 3 years ago

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.

mfanuzzi commented 3 years ago

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.

arindam1993 commented 3 years ago

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.

Pessimistress commented 3 years ago

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: