I'd like to define BASE_URLs for production and development as environment variables to be used in API calls like this:
DEV_BASE_URL="http://127.0.0.1:8080"
PROD_BASE_URL=";
I have defined them in an .env
file then in my ponent I tried to import them like:
import {env} from '$env/dynamic/public'
console.log('DEV_BASE_URL is:', env.DEV_BASE_URL)
But I get DEV_BASE_URL is: undefined
in the console.
The docs about different types of envs has just added to my confusions. The docs is awful.
So appreciate your help to resolve these global variables in an idiomatic manner.
I'd like to define BASE_URLs for production and development as environment variables to be used in API calls like this:
DEV_BASE_URL="http://127.0.0.1:8080"
PROD_BASE_URL="https://example."
I have defined them in an .env
file then in my ponent I tried to import them like:
import {env} from '$env/dynamic/public'
console.log('DEV_BASE_URL is:', env.DEV_BASE_URL)
But I get DEV_BASE_URL is: undefined
in the console.
The docs about different types of envs has just added to my confusions. The docs is awful.
So appreciate your help to resolve these global variables in an idiomatic manner.
Share Improve this question asked Nov 5, 2022 at 5:39 blnksblnks 1,1612 gold badges10 silver badges21 bronze badges1 Answer
Reset to default 8- first of all, let's change the
.env
content like follows
PUBLIC_DEV_BASE_URL="http://127.0.0.1:8080"
PUBLIC_PROD_BASE_URL="https://example."
- then in your
svelte
files import them like this
import { PUBLIC_DEV_BASE_URL, PUBLIC_PROD_BASE_URL } from '$env/static/public'
- to load env vars based on the server mode, you should create a
.env
file for each mode, in this caseproduction | development
like follows
.env.development
PUBLIC_BASE_URL="http://127.0.0.1:8080"
.env.production
PUBLIC_BASE_URL="https://example."
- now you just import that variable and used
import { PUBLIC_BASE_URL } from '$env/static/public'
for more information on how Sveltekit
handles env vars check the documentation https://kit.svelte.dev/docs/modules#$env-static-public
for more information on how Vite
handles env vars check this link https://vitejs.dev/guide/env-and-mode.html#modes