I am building a fully static website with SvelteKit. I am using the @sveltejs/adapter-static version 3.0.5.
I want to load inside my webpage a simple table. For various compatibility and shareability reasons, I would like to store this table in a known data format like csv, json, parquet, etc.
First question: Considering the latest design of SvelteKit where should these files live?
Should they live in the static
folder? Or in a top-level data
folder? Or in a $lib/data
folder?
Second question: Once I decided the best place to put these files, what is the intended/best way of loading these files?
My project structure follow the template skeleton:
src/
├── app.html
├── index.test.js
├── lib
│ ├── data
│ │ └── data_1000.csv
│ └── index.js
└── routes
├── +layout.js
├── +page.js
└── +page.svelte
The top of +page.svelte
looks like:
<script>
/** @type {import('./$types').PageData} */
export let data;
</script>
+layout.js
looks like:
export const prerender = true;
and +page.js
looks like:
/** @type {import('./$types').PageLoad} */
export function load() {
...
}
I tried using the fetch
API but I got errors related to not being able of using relative routes (I guess it is related to using a file system path instead of a URL) and I couldn't make the require fs
from the Node documentation to work.
The location does not really matter that much, but static
is mainly for resources that need a fixed path e.g. things like robots.txt
.
If the data is used in many places, $lib
is a good place. If it's relevant to just one route, you may as well put it directly in that route's directory.
To get the data, I would use an import
. If the data is text-based you can e.g. use a ?raw
query parameter to get the contents. This is a Vite feature, which does not handle binary properly, though.
For any other format, find or create a Vite plugin that e.g. checks the file extension and reads the file contents in a way that makes sense for the format. Since the plugin runs at build time you have access to the full Node APIs that can read the file and do whatever else with it.
(If the path can be somewhat dynamic, e.g. different files are loaded based on user interaction, you will probably need a glob import using this approach.)