Mapbox-gl typing won't allow accessToken assignment

前端 未结 3 2529
日久生厌
日久生厌 2021-02-20 00:54

I\'m using the mapbox-gl library with TypeScript, and I\'ve installed its community sourced type definitions with @types/mapbox-gl. When I try to import and set an

相关标签:
3条回答
  • 2021-02-20 01:41

    Here's a temporary workaround I've been using:

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

    Explanation

    Since the object was redefined to use a custom setter which places the token inside an internal closure - we can call the setter function directly as shown in the example.

    Diving a little deeper, we can see that es6 modules are constants by definition: https://github.com/Microsoft/TypeScript/issues/6751#issuecomment-177114001

    we can then do something like: (mapboxgl as any).accessToken = ... which will work.

    0 讨论(0)
  • 2021-02-20 01:43

    For those finding this now ... You don't even need to set the Mapbox accessToken this way, it can be passed in as an option (since v1.2)

    const map = new mapboxgl.Map({
      accessToken: '...',
      container: '...',
      style: '...',
    });
    

    Pity it's not the method used in any of the examples (yet).

    Docs: https://docs.mapbox.com/mapbox-gl-js/api/#map

    1.2 release notes: https://github.com/mapbox/mapbox-gl-js/releases/tag/v1.2.0

    PR that adds it: https://github.com/mapbox/mapbox-gl-js/pull/8364

    0 讨论(0)
  • 2021-02-20 01:43

    You can also use this format:

    (mapboxgl as typeof mapboxgl).accessToken = ...
    
    0 讨论(0)
提交回复
热议问题