最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to define BASE_URLs in sveltekit? - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

1 Answer 1

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 case production | 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

发布评论

评论列表(0)

  1. 暂无评论