#How to run a script client-side only?

5 messages · Page 1 of 1 (latest)

iron aspen
#

I am using Leaflet library to render maps. My script is something as simple as this

<template>
<div id="map">This is a map.</div>
</template>

<script setup lang="ts">
import L from "leaflet"

onMounted(() => {
    L.map(map).setView([51.505, -0.09], 13)
    console.log(L)
})
</script>

<style lang="postcss">
#map {
    height: 180px;
}
</style>

I thought that everything within onMounted would only be run client-side, but I have the error "window is not defined" from the server side. Doing something as simple as console.log(L) still results in this error.

Please advise...

olive lynx
#

Hi 👋 that's because leaflet contains some side-effects

#

this might be a bug since the imports should also be treeshaken... i think ? 🤔

#

The workaround is to declare your component client only with .client or to wrap your component within a <ClientOnly>

iron aspen
#

I manage to create a separate component for Leaflet map, and render that component within <ClientOnly>, and it works.