I'm trying to create a system in my SvelteKit app where it shows you info about the current app version (ideally a Git commit hash and description) on a certain page. I tried using Vite's define feature to do this at build time but it doesn't seem to work. How do I add something like this?
Here's an example of what I tried to do:
Vite config in svelte.config.js
vite: () => ({
define: {
'__APP_VERSION__': JSON.stringify('testfornow')
}
})
index.svelte:
<script lang="ts">
const version: string = __APP_VERSION__;
</script>
<p>Current App version: {version}</p>
This is how I managed to make it work:
// 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);
const config = {
kit: {
// ...
vite: {
define: {
'__APP_VERSION__': JSON.stringify(pkg.version),
}
},
},
// ...
};
<h2>Version: {__APP_VERSION__}</h2>
Quite similar to your example, hope it helps!
I have a blank file version.txt in my static directory. Then I use something like this in my packaging script.
git describe --tags 2> /dev/null || git rev-parse --short HEAD > build/assets/version.txt
This tries to find a tag (if any) or just outputs latest commitId. In my app I fetch /version.txt and display its content where appropriate.