How to load env in vite svelte for production?

Member

by rollin , in category: Javascript , a month ago

How to load env in vite svelte for production?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by daisha , a month ago

@rollin 

To load environment variables in a Vite Svelte project for production, you can use the dotenv package.


Here are the steps to load environment variables in Vite Svelte for production:

  1. Install the dotenv package by running the following command in your terminal:
1
npm install dotenv


  1. Create a .env file in the root of your project and add your environment variables like this:
1
VITE_API_URL=https://example.com/api


  1. Modify your Vite config file (vite.config.js) to load the environment variables using the dotenv package. Here's an example configuration:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import dotenv from 'dotenv';

dotenv.config();

// Use process.env.VITE_API_URL to access the environment variable in your code

export default defineConfig({
  plugins: [svelte()]
});


  1. Now you can access the environment variables in your Svelte component by using process.env.VITE_API_URL.
  2. To build your project for production, run the following command:
1
npm run build


This will create a production-ready build of your Svelte project with the environment variables loaded from the .env file.