reactjsangulartypescriptmapboxmapbox-gl

Directly setting accessToken to Mapbox throws Imports are immutable error


When accessToken is directly set to mapboxgl, it throws an error.

Imports are immutable in Javascript. To modify the value of this import, you must export a setter function in the imported file (e.g "setAccessToken") and then import and call that function here instead.

import * as mapboxgl from 'mapbox-gl';

mapboxgl.accessToken = 'YOUR_TOKEN';

Solution

  • To avoid different kind of errors like

    1. Imports are Immutable error during the compilation phase when directly setting this as

      mapboxgl.accessToken = 'YOUR_TOKEN';

    2. set is not a function error on the browser when you have hosted your compiled artifact with the static method

      Object.getOwnPropertyDescriptor(mapboxgl, "accessToken"). set(YOUR_TOKEN');

    You nee to directly set this on the ACCESS_TOKEN property present on mapboxgl.config

    import * as mapboxgl from 'mapbox-gl';
    
    mapboxgl.config.ACCESS_TOKEN = 'YOUR_TOKEN';