I would like to display a version that is declared in the package.json file in the footer of my site
How can I do this?
I found this FAQ explanation in their documentation, but unfortunately I don't know to access it from my component
// svelte.config.js
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
const file = fileURLToPath(new URL('package.json', import.meta.url));
const json = readFileSync(file, 'utf8');
const pkg = JSON.parse(json);
You can use vite.define
to do this:
const config = {
kit: {
vite: {
define: {
VERSION: pkg
}
}
}
};
and in your component:
<script>
const version = VERSION;
</script>
<span>{version}</span>
edit on 06.07.2023
Seems the setup has changed in the time since the answer.
Now you can do this in vite.config.js
as below:
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
const file = fileURLToPath(new URL('package.json', import.meta.url));
const json = readFileSync(file, 'utf8');
const pkg = JSON.parse(json);
export default defineConfig({
plugins: [sveltekit()],
define: {
PKG: pkg
}
});
and use
<p>{PKG.version}</p>