Stiegi
Stiegi

Reputation: 1805

Sveltekit + Typescript: Environment variables build error

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?

Upvotes: 28

Views: 15181

Answers (4)

Stiegi
Stiegi

Reputation: 1805

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).

Upvotes: 66

jhickok
jhickok

Reputation: 997

This problem still exists for me in Dec 2024.

Only way I could solve the error was to add this to tsconfig.json at the root level.

"include": [
    "./src",
    ".svelte-kit/ambient.d.ts" // added this
]

Upvotes: 2

yavnelf
yavnelf

Reputation: 355

Quick fix for Svelte 5

<script>
    import { env } from '$env/dynamic/public';
</script>

<main
    style:background={env.PUBLIC_THEME_BACKGROUND}
    style:color={env.PUBLIC_THEME_FOREGROUND}
>
    {env.PUBLIC_THEME_FOREGROUND} on {env.PUBLIC_THEME_BACKGROUND}
</main>

Upvotes: -2

lkostka
lkostka

Reputation: 751

Alternative solution, check whether or not your env variable is prefixed with 'PUBLIC'. If yes, you can import it from the module '$env/static/public'. If not, you can import it from the module '$env/static/private'

Upvotes: -2

Related Questions