I want to use environment variables in my Sveltekit app - it works fine on dev server, but I get this build error:
Error: 'PUBLIC_KEY' is not exported by $env/static/public, imported by src/routes/+layout.svelte
So Svelte has this module that helps with env stuff: https://kit.svelte.dev/docs/modules#$env-static-public
I have a simple .env file like this:
PUBLIC_KEY=123
Now the IDE throws the same type error like the build error, but I can fix that by adding this to my types.d.ts
file:
declare module '$env/static/public' {
export const PUBLIC_KEY: string;
}
Now the type error in my IDE is gone, for testing I just add this to my +layout.svelte file:
<script lang="ts">
import { PUBLIC_KEY } from '$env/static/public';
</script>
<div>{ PUBLIC_KEY }</div>
The content 123 is rendered on dev server, so it works. However, if I run npm run build
, the error from above occurs. Even putting a @ts-ignore
above the import doesn't help.
So my question is: what do I have to do to make TS play along?
I found the answer - in a comment of the PR for that feature. Would be nice if that was in the documentation.
However, for those who face that issue and land here: you have to run svelte-kit sync
- it will create a type file based upon your .env files.
You can use npm run check
- this includes the sync command.
You don't need to write the types yourself like I did in my question! Just run npm run check
(make sure that the corresponding .env file exists when doing so).