Search code examples
chart.jsvitesveltekit

Sveltekit, Depencencies working in dev but not loading directly in the routed page after build


In a sveltekit project where everything works in dev, some dependencies seems not to be working when build at routed pages.

In specific charts.js is working in dev well, but is not working in a routed page /page when the it is build for production.

It is hard to debug as there is no error messages, but there are significantly less GET request when going to /page and if I go to the main page and then use a <a/> link to the route, everything works fine.

What could be the reason behind this? Am I missing some configuration? Probably the route is not expected to be fetched directly?

pd: I'm using svelte-chartjs library.

the component looks like this:

<script lang="ts">
  import { Doughnut } from 'svelte-chartjs';
  export datax = 10
  export datay = 20

  import {
    Chart as ChartJS,
    Title,
    Tooltip,
    Legend,
    ArcElement,
    CategoryScale,
  } from 'chart.js'


  let chart: Doughnut;
  let data = {
      labels: ['Pension', 'Monthly paid out salary', 'Tax Under', 'Tax Over'],
    datasets: [
      {
      label: 'Danish Kronws',
      data: [datax , datay],
      backgroundColor: [
        'rgba(255, 134,159,0.4)',
        'rgba(98,  182, 239,0.4)',
      ],
      borderWidth: 2,
      borderColor: [
        'rgba(255, 134, 159, 1)',
        'rgba(98,  182, 239, 1)',
      ],
      },
    ],
  };

  ChartJS.register(Title, Tooltip, Legend, ArcElement, CategoryScale);

  $: {if (chart) {
      chart.data.datasets[0].data = [datax ,datay]
    }
  }

</script>

<div class="chart">
  <Doughnut bind:chart data={data} options={options} />

</div>

<style>
  .chart{
    border-radius: 10px;
    box-shadow:0 0 15px 4px rgba(0,0,0,0.06);
    padding: 10px;
    width: 600px;
  }

</style>

Solution

  • When navigation to the page works but direct access does not, that is a sign that there are issues with server-side rendering. The first access to a page is rendered on the server by default which can cause issues.

    E.g. your page code has to avoid accessing any browser APIs outside of onMount as those will not be available on the server. Check the console of the server process and the console in the browser for errors.

    You can also turn off SSR by adding an export to +page.js/ts.

    export const ssr = false;
    

    I would only recommend this for finding out whether SSR is the problem. Turning it off permanently should only be done in rare occasions when absolutely necessary.