Gatsby: How can I include mapbox-gl in Gatsby?

Created on 23 Jul 2018  Â·  11Comments  Â·  Source: gatsbyjs/gatsby

I'm trying to include the https://github.com/mapbox/mapbox-gl-js in a Gatsby project, but I'm getting an error during build. Works nicely in dev mode.

(If someone wants to try this should be easier: https://github.com/alex3165/react-mapbox-gl)

...{}),!this.workerSources[e][t][r]){var i={send:function(t,r,i){n.actor.send(t,r,i,e);}};this.workerSources[e][t][r]=new this.workerSourceTypes[t](i,this.getLayerIndex(e));}return this.workerSources[e][t][r]},He.prototype.getDEMWorkerSource=function(e,t){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][t]||(this.demWorkerSources[e][t]=new D),this.demWorkerSources[e][t]},"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope&&new He(self),He});
  32 |


  WebpackError: ReferenceError: self is not defined

  - mapbox-gl.js:29
    [lib]/[mapbox-gl]/dist/mapbox-gl.js:29:206

  - mapbox-gl.js:22 define
    [lib]/[mapbox-gl]/dist/mapbox-gl.js:22:1

  - mapbox-gl.js:33
    [lib]/[mapbox-gl]/dist/mapbox-gl.js:33:1

  - mapbox-gl.js:3
    [lib]/[mapbox-gl]/dist/mapbox-gl.js:3:1

  - mapbox-gl.js:6 Object../node_modules/mapbox-gl/dist/mapbox-gl.js
    [lib]/[mapbox-gl]/dist/mapbox-gl.js:6:2

  - bootstrap:19 __webpack_require__
    lib/webpack/bootstrap:19:1

  - map.js:21 Object../node_modules/react-mapbox-gl/lib/map.js
    [lib]/[react-mapbox-gl]/lib/map.js:21:1

  - bootstrap:19 __webpack_require__
    lib/webpack/bootstrap:19:1

  - index.js:3 Object../node_modules/react-mapbox-gl/lib/index.js
    [lib]/[react-mapbox-gl]/lib/index.js:3:1

  - bootstrap:19 __webpack_require__
    lib/webpack/bootstrap:19:1


  - bootstrap:19 __webpack_require__
    lib/webpack/bootstrap:19:1

  - sync-requires.js:8 Object../.cache/sync-requires.js
    lib/.cache/sync-requires.js:8:51

  - bootstrap:19 __webpack_require__
    lib/webpack/bootstrap:19:1

  - static-entry.js:9 Module../.cache/static-entry.js
    lib/.cache/static-entry.js:9:22

  - bootstrap:19 __webpack_require__
    lib/webpack/bootstrap:19:1


error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
question or discussion

Most helpful comment

For this to work in the latest version of Gatsby, you need to modify https://github.com/gatsbyjs/gatsby/issues/6667#issuecomment-409836864 to this:

exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
  if (stage === "build-html") {
    actions.setWebpackConfig({
      module: {
        rules: [
          {
            test: /mapbox-gl/,
            use: loaders.null(),
          },
        ],
      },
    })
  }
}

so loaders.null() instead of null-loader, as per https://www.gatsbyjs.org/docs/debugging-html-builds/#fixing-third-party-modules

All 11 comments

I'm not sure about Mapbox, but with Leaflet the problem is that it expects to find window, which isn't available in production build. The fact it works in develop means it may be a similar problem. I had to use a silly workaround to load the library only on componentDidMount: https://github.com/aerian-studios/aerian-site-rebuild/blob/master/src/components/MapView/MapView.tsx

As @ascorbic mentions, this is typically caused by libraries that expect to always run in a browser environment. During gatsby build, Gatsby runs your code in a Node.js environment to render out all your static html files, so browser globals like window don't exist.

Maybe that's not exactly what's happening here (I don't think self is a browser global?), but it'd be a good first step to investigate. There's a bit of info here https://www.gatsbyjs.org/docs/debugging-html-builds/

Also searching the mapbox-gl-js repo for ReferenceError: self is not defined provides a few results that might be relevant.

Would that work in Gatsby? https://github.com/mapbox/mapbox-gl-js/issues/4593#issuecomment-397872590

(can't test it at the moment)

Here is the minimal example that works locally, but fails during build: https://github.com/lipis/mapbox-gatsby

I didn't manage to make it work.. can anyone else take a look?

(Feel free to use the access key, it's for testing purposes only and I'll delete it afterwards)

Thanks to @herrmannplatz!!

In gatsby-node.js:

exports.onCreateWebpackConfig = ({ actions, stage }) => {
  if (stage === "build-html") {
    actions.setWebpackConfig({
      module: {
        rules: [
          {
            test: /mapbox-gl/,
            use: ['null-loader']
          },
        ],
      }
    })
  }
};

I wasn't able to get mine to work as per the above suggestions. I ended up mocking my implementation to get it to work.

let mapboxgl
let ReactMapboxGl = {}

if (typeof window !== `undefined`) {
  mapboxgl = require('mapbox-gl')
  ReactMapboxGl = require('react-mapbox-gl')
} else {
  ReactMapboxGl.Map = () => {
    return class Mock extends React.Component {
      constructor() {
        super()
      }
      render() {
        return <div />
      }
    }
  }
}

const Map = ReactMapboxGl.Map({
  accessToken:  '[your-token-here]',
})

class DirectoryMap extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return (
      <div className="directory-map">
        <Map
          ref={e => {
            this.map = e
          }}
          zoom={[11]}
          speed={[0.6]}
        >
        </Map>
      </div>
    )
  }
}

For this to work in the latest version of Gatsby, you need to modify https://github.com/gatsbyjs/gatsby/issues/6667#issuecomment-409836864 to this:

exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
  if (stage === "build-html") {
    actions.setWebpackConfig({
      module: {
        rules: [
          {
            test: /mapbox-gl/,
            use: loaders.null(),
          },
        ],
      },
    })
  }
}

so loaders.null() instead of null-loader, as per https://www.gatsbyjs.org/docs/debugging-html-builds/#fixing-third-party-modules

@jonlow I tried this but it is not working for me, I am not really sure what is going on in the code above you explain or take a look at my repo here to see why I cannot load mapbox in production?

Thanks for any help in advance
https://github.com/arhoy/fashion-two

@arhoy if you don't mind i'll take a look tomorrow and see if i can provide you with a solution to the issue. Do you mind waiting a bit?

That would be great! Thank you so much

On Mon, Nov 4, 2019 at 6:47 PM jonniebigodes notifications@github.com
wrote:

@arhoy https://github.com/arhoy if you don't mind i'll take a look
tomorrow and see if i can provide you with a solution to the issue. Do you
mind waiting a bit?

—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/gatsbyjs/gatsby/issues/6667?email_source=notifications&email_token=ACPMK7NZWNNS4IQZS3LCMBDQSDGDXA5CNFSM4FLKFWUKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEDBKH3I#issuecomment-549626861,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/ACPMK7NPZHZMYJLZWJWXDR3QSDGDXANCNFSM4FLKFWUA
.

For those trying to modify onCreateWebpackConfig in gatsby-node.js, here's an example of modifying existing settings to add special handling for mapboxGL: https://github.com/brendan-ward/gatsby-starter-mapbox/blob/master/gatsby-node.js

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kalinchernev picture kalinchernev  Â·  3Comments

magicly picture magicly  Â·  3Comments

dustinhorton picture dustinhorton  Â·  3Comments

KyleAMathews picture KyleAMathews  Â·  3Comments

jimfilippou picture jimfilippou  Â·  3Comments