Basic Svelte
Introduction
Bindings
Classes and styles
Attachments
Advanced Svelte
Advanced reactivity
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
Some environment variables can safely be exposed to the browser. In this exercise, we’ll use two of them to control the page’s colour scheme.
Add values to the two environment variables in .env:
THEME_BACKGROUND="steelblue"
THEME_FOREGROUND="bisque"Next, create src/env.js. Import defineEnvVars from @sveltejs/kit/env, and configure both variables with public: true:
import { defineEnvVars } from '@sveltejs/kit/env';
export const variables = defineEnvVars({
THEME_BACKGROUND: {
public: true
},
THEME_FOREGROUND: {
public: true
}
});You can now import the variables into src/routes/+page.svelte from $app/env/public:
<script>
const THEME_BACKGROUND = 'white';
const THEME_FOREGROUND = 'black';
import {
THEME_BACKGROUND,
THEME_FOREGROUND
} from '$app/env/public';
</script><script lang="ts">
const THEME_BACKGROUND = 'white';
const THEME_FOREGROUND = 'black';
import {
THEME_BACKGROUND,
THEME_FOREGROUND
} from '$app/env/public';
</script>Environment variables are dynamic by default, meaning their values are read when the app starts. If a variable is known when the app is built, you can add static: true to its configuration to inline its value into the bundle, enabling optimisations like dead-code elimination.
Prior to SvelteKit 3 you didn’t have the option to declare an
env.jsfile - instead, you had to prefix your environment variables withPUBLIC_to make them available via$env/dynamic/publicand$env/static/public.
<script>
const THEME_BACKGROUND = 'white';
const THEME_FOREGROUND = 'black';
</script>
<main
style:background={THEME_BACKGROUND} style:color={THEME_FOREGROUND}>
{THEME_FOREGROUND} on {THEME_BACKGROUND}</main>
<style>
main {position: fixed;
display: flex;
align-items: center;
justify-content: center;
left: 0;
top: 0;
width: 100%;
height: 100%;
font-size: 10vmin;
}
</style>