1

I'm in the middle of a course and currently trying to implement mapbox.js . I have followed all of the instructions directly from the mapbox documentation but am receiving an error in the console:

Uncaught ReferenceError: require is not defined
<anonymous> http://localhost:8000/js/mapbox.js:3

Here is my mapbox.js file:

var mapboxgl = require('mapbox-gl/dist/mapbox-gl.js');

mapboxgl.accessToken =
  'pk.eyJ1IjoiYnJhbmF1c3QiLCJhIjoiY2tnOHVibGllMDVuYjJ5cHFmbmpucndwZSJ9.KBzYV-QSHSChEb6QJpNpdg';
var map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/streets-v11',
});

and I am appending to the head of my base file inside a separate .pug file :

block append head
link(href='https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css' rel='stylesheet')

enter image description here

Brandon Austin
  • 162
  • 1
  • 1
  • 10
  • Which documentation are you reading? I can't see any mention of `require` here: https://docs.mapbox.com/mapbox-gl-js/api/ – Quentin Oct 14 '20 at 18:20
  • I just added a picture of the instructions given to me from their website. Thanks for your help – Brandon Austin Oct 14 '20 at 18:22
  • I can't look at the documentation for context if I only see a screenshot of a small portion of it! – Quentin Oct 14 '20 at 18:32
  • Does this answer your question? [Client on node: Uncaught ReferenceError: require is not defined](https://stackoverflow.com/questions/19059580/client-on-node-uncaught-referenceerror-require-is-not-defined) – shreyasm-dev Oct 14 '20 at 19:12

1 Answers1

2

require is a function in node js (server side) only and not in the browser.

See the answer to using require in the browser here: Node-style require for in-browser javascript?

or

Alternatively, just add script tag linking to the mapbox js files and remove your require statement.

So add this to your html: <script src='https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js'></script>

Then change your code to be:

mapboxgl.accessToken =
  'pk.eyJ1IjoiYnJhbmF1c3QiLCJhIjoiY2tnOHVibGllMDVuYjJ5cHFmbmpucndwZSJ9.KBzYV-QSHSChEb6QJpNpdg';
var map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/streets-v11',
});
anon
  • 816
  • 5
  • 17