Unable to use .env files with Vite and Vue 3

70 Views Asked by At

I am using Vue 3 with vite as my dev server... I have two .env files configured for my vite setup, .env and .env.development, and I seem unable to use the variables within them...

.env

VITE_API_KEY="1234"
VITE_API_URL="https://www.myapi.com"

.env.development

VITE_API_KEY="5678"
VITE_API_URL="https://www.staging.myapi.com"

Could someone help me understand why when I use my variables like this import.meta.env.VITE_API_URL, I just get this in the console; Cannot read properties of undefined (reading 'VITE_API_URL'), and if i use process. I get Process is undefined.

I'd also like to add I'm not using dotenv or anything like that...

Good trawl around StackOverflow, but nothing has helped me so far...

I would appreciate any help

2

There are 2 best solutions below

2
Hardik On

install this two package

env-cmd,
dotenv

package.json file add this cmd

script:{    
    "local": "env-cmd -f .env vite",
    "dev": "env-cmd -f .env.development vite", 
    //Other
}

using

const ApiBaseUrl = import.meta.env.VITE_BASE_URL

local env run that time run npm run local development env run that time npm run dev

add both .env file one more key VITE_NODE_ENV=

0
Takuhii On

So I've kind of solved it... Basically Vite doesn't load .env files by default as the files to load can only be determined after evaluating the Vite config, for example, the root and envDir options affect the loading behaviour. However, you can use the exported loadEnv helper to load the specific .env file if needed.

There is a way to load a specific .env file, but this still doesn't allow vite to access the .env variables in the vite.config.js