Nato Boram
Nato Boram

Reputation: 4974

How can I use Vite env variables in svelte.config.js?

For example, in .env.local, I have

VITE_BASE=/sveltekit-ghpages

I can access this variable inside src using import.meta.env.VITE_BASE. But inside svelte.config.js, it doesn't work.

How can I use Vite env variables in svelte.config.js?

Upvotes: 4

Views: 3842

Answers (2)

hassan zarghami
hassan zarghami

Reputation: 179

To use Vite environment variables in svelte.config.js, you can't directly access process.env.VITE_ variables because Vite only injects them into the client-side code during the build. However, you can use dotenv to load these environment variables in your config files.

First, install dotenv to load the environment variables in svelte.config.js:

npm install dotenv --save

Then, you can import and configure dotenv at the top of your svelte.config.js file to load the .env file:

import { config } from 'dotenv';
import adapter from '@sveltejs/adapter-auto';

// Load environment variables
config();

export default {
  kit: {
    adapter: adapter(),
    vite: {
      define: {
        'process.env.VITE_APP': JSON.stringify(process.env.VITE_APP)
      }
    }
  }
};

Upvotes: 0

Shriji Kondan Elangovan
Shriji Kondan Elangovan

Reputation: 1109

Option 1:

If you are already using dotenv if your project then you can do this in your svelte.config.js file


import 'dotenv/config';

console.log("config", process.env.FOO)

Option 2:

If your node script is overloaded with environment variables, for example


...

"scripts": {
        "build": "FOO=BAR vite build"
}

...

then you can use console.log( process.env.FOO) without having to install dotenv svelte.config.js file

Upvotes: 2

Related Questions