0

Sample code:

<div>
    <canvas id="example"></canvas>
</div>

<script>
    import { onMount } from 'svelte'

    import Chart from 'chart.js/auto' // Version 4.3.3

    onMount(async () => {
        const zoomPlugin = await import('chartjs-plugin-zoom') // Version 2.0.1 | Why import in onMount: https://stackoverflow.com/a/76728081/9157799

        Chart.register(zoomPlugin)

        new Chart(
            document.getElementById('example'),
            { // From https://www.chartjs.org/chartjs-plugin-zoom/latest/guide/usage.html
                type: 'line',
                data: {
                    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
                    datasets: [{
                        label: 'My First Dataset',
                        data: [65, 59, 80, 81, 56, 55, 40],
                        fill: false,
                        borderColor: 'rgb(75, 192, 192)',
                        tension: 0.1
                    }]
                },
                options: {
                    plugins: {
                        zoom: {
                            zoom: {
                                wheel: {
                                    enabled: true,
                                },
                                pinch: {
                                    enabled: true
                                },
                                mode: 'xy',
                            }
                        }
                    }
                }
            }
        )
    })
</script>

Without SvelteKit, it works (REPL).

M Imam Pratama
  • 998
  • 11
  • 26
  • 1
    Do not query the DOM like that, it violates component boundaries/can potentially select the wrong element. Either use [`bind:this`](https://svelte.dev/docs/element-directives#bind-this) or better yet, an [action](https://svelte.dev/docs/element-directives#use-action), that way you do not even need `onMount`. – H.B. Aug 16 '23 at 08:07
  • @H.B. Thanks for the tips! Note to self: [`use:action` vs onMount example](https://stackoverflow.com/q/58068865/9157799). – M Imam Pratama Aug 18 '23 at 02:19

1 Answers1

0
1. Disable SSR for the page:
// +page.js
export const ssr = false;
2. import zoomPlugin normally.
<div>
    <canvas id="example"></canvas>
</div>

<script>
    import { onMount } from 'svelte'

    import Chart from 'chart.js/auto' // Version 4.3.3
    import zoomPlugin from "chartjs-plugin-zoom"

    Chart.register(zoomPlugin)

    onMount(() => {
        new Chart(
            document.getElementById('example'),
            { // From https://www.chartjs.org/chartjs-plugin-zoom/latest/guide/usage.html
                ...
            }
        )
    })
</script>
M Imam Pratama
  • 998
  • 11
  • 26