Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create React App Excluding mapbox-gl explicitly from transpilation

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

like image 806
crg Avatar asked Sep 05 '26 13:09

crg


1 Answers

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.

like image 116
crg Avatar answered Sep 07 '26 01:09

crg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!