0
votes

I'm building a svelte app with sapper, and want to use leaflet js for mapping.

Leaflet refers to the "window" object, which is not available on the SSR side; I wondered if there's a way to trick Sapper into thinking "window" exists?

The app is built with the standard rollup config from the sapper website.

I am currently doing this in map.svelte:

<svelte:head>
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
          integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
          crossorigin=""/>
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
            integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
            crossorigin=""></script>
</svelte:head>
<script>

import {onMount} from 'svelte';

export let map;

onMount(async () => {

    map = L.map('map', 
      { zoomControl: false })
      .setView([57.6773, 11.9583], 13);
   
    var osm = L.tileLayer('https://{s}.tile.osm.org/{z}/{x}/{y}.png', {
      name: 'Open Street Map',
      maxZoom: 24,
      attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo( map );

});
</script>

This works fine, but given the modules I am to develop to work with leaflet, I'd prefer to use the

import "leaflet/dist/leaflet.css";
import L from 'leaflet';

way of using Leaflet.

Does anyone know if this can be done with Sapper?

1
you can check how this is implemented: github.com/beyonk-adventures/svelte-mapbox/tree/master/srctoHo

1 Answers

0
votes

Got inspiration here;

and did this:

<script>
import "leaflet/dist/leaflet.css";
import {onMount} from 'svelte';

export let map;
let L;

onMount(async () => {

  const l = await import('leaflet');
  L = l.default;

  map = L.map('map', 
    { zoomControl: false })
    .setView([57.6773, 11.9583], 13);

  new L.Control.Zoom({ position: 'bottomright' })
  .addTo( map );

  var osm = L.tileLayer('https://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    name: 'Open Street Map',
    maxZoom: 24,
    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
  }).addTo( map );

});
</script>

Works :)