Svelte running preview build can't load local json files

401 Views Asked by At

I have a svelte app I've been working on for some time and I'm ready to deploy it to the hosting service I have. When I create the build using npm run build there are no errors. Then when I preview the build npm run preview and try to navigate to certain pages of the site I run into "Error: Not found: /data/gameData/{gameID}.json". When running the app npm run dev this isn't an issue and the page is able to find the local json files no problem. It isn't until I preview the build I have ready for production that it suddenly can't find local json files.

Below is the file in question /src/routes/game/[gameId]/+page.svelte (note: I am using dynamic imports with dataPath, could that be the culprit?):

<script>
    import { onMount } from 'svelte';
    import { page } from '$app/stores';
    const gameId = $page.params.gameId;

    let jsonData, gameRoutes, gameLocos, gameName, gameSysnopsis, routesCopy, locosCopy;
    
    const dataPath = `../../../data/gameData/${gameId}.json`;
    import locoData from '../../../data/locoData/allLocos.json';
    

    // Filter out any locos not part of the current gameId  
    const result = locoData.locos.filter(loco => loco.game === gameId);
    
    onMount(async () => {
        jsonData = (await import(/* @vite-ignore */ dataPath)).default;
        gameRoutes = jsonData.dlcRoutes;
        gameLocos = jsonData.dlcLocos
        gameName = jsonData.name;
        gameSysnopsis = jsonData.synopsis;
        routesCopy = jsonData.routesCopy;
        locosCopy = jsonData.locosCopy;
    });
</script>
...

I also have the @sveltejs/adapter-static adapter setup in svelte.config.js. I am using static because I plan to deploy the website to a HostGator shared hosting setup using FTP. I think that's the right choice for adapters, but I could be wrong because I'm new to Svelte (and web dev in general).

1

There are 1 best solutions below

0
Oscar Hermoso On BEST ANSWER

It's almost certainly because of the dynamic imports. When your Svelte app builds for production, any JSON files that were available in dev mode are not included in the final build, because:

  1. They are not actually imported at build time, so they don't end up in the bundle... and ;
  2. Your import path may not be the same at runtime.

You could maybe get it working by putting the JSON files into the Svelte static directory, which are always included, or using Vite glob imports to guarantee that the files are included at build time.

But it would probably be wiser set up a database for the data, and deploy your application with a non-static adapter, to securely connect to the database from the Svelte-kit backend.

For example, you could use Vercel, or Fly.io to for hosting with a Postgres database.