75

With the following .env in my Vite project:

# To prevent accidentally leaking env variables to the client, only
# variables prefixed with VITE_ are exposed to your Vite-processed code

VITE_NAME=Wheatgrass
VITE_PORT=8080

How can I use VITE_PORT in my vite.config.js?

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
Matt
  • 8,758
  • 4
  • 35
  • 64

5 Answers5

137

You can load the app level env variables and add them to the Node level env variables:

import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';


export default ({ mode }) => {
    process.env = {...process.env, ...loadEnv(mode, process.cwd())};

    // import.meta.env.VITE_NAME available here with: process.env.VITE_NAME
    // import.meta.env.VITE_PORT available here with: process.env.VITE_PORT

    return defineConfig({
        plugins: [vue()],

        server: {
            port: parseInt(process.env.VITE_PORT),
        },
    });
}
robere2
  • 1,689
  • 2
  • 16
  • 26
Matt
  • 8,758
  • 4
  • 35
  • 64
  • 20
    If the above does not work for you (e.g. you want to import a variable that is not prefixed with `VITE_`. Try this: `process.env = { ...process.env, ...loadEnv(mode, process.cwd(), '') };` The prefx (3rd argument) does make the difference here. – F. Müller Feb 07 '22 at 13:27
  • Regarding the `server.port` assignment, my `vite.config.ts` gives me the error "Type 'string' is not assignable to type 'number'". How do I fix that? – Brent Arias Jan 12 '23 at 19:46
  • @BrentArias Environment variables are always strings, but the type definitions for Vite expect a number there. Use [parseInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt). – robere2 Jan 14 '23 at 21:26
  • thanks it works in file `vite.config.ts` – PACE Apr 01 '23 at 16:46
  • CAUTION: Better use `Object.assign(process.env, loadEnv(mode, process.cwd()))` instead of destructuring `process.env`! When I added the env variables like that, the keys lost their case-insensitivity somehow (running on Windows). To be specific, running `npx vite` failed for me because `process.env.SYSTEMROOT` is undefined, while `process.env.SystemRoot` IS defined. This does not happen anymore when I use `Object.assign` instead. – StrikeAgainst Apr 09 '23 at 14:09
6

If the above solution by @matt doesnt work for you then change the vite.config.ts/ vite.config.js like below

1st Solution

import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';

export default defineConfig(({ mode }) => {

const env = loadEnv(
  'mock', 
  process.cwd(),
  '' 
)
  const processEnvValues = {
    'process.env': Object.entries(env).reduce(
      (prev, [key, val]) => {
        return {
          ...prev,
          [key]: val,
        }
      },
      {},
    )
  }

  return {
    plugins: [vue()],
    define: processEnvValues
  }
}

2nd Solution

import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';


export default ({ mode }) => {
    process.env = Object.assign(process.env, loadEnv(mode, process.cwd(), ''));

    return defineConfig({
        plugins: [vue()],
    });
}

Goutham J.M
  • 1,726
  • 12
  • 25
1

Maybe this can be usefull for someone that is working with react and vite

vite.config.js

import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react";

// https://vitejs.dev/config/
// export default defineConfig({
//   plugins: [react()],
// })

export default defineConfig(({ mode }) => {
  const env = loadEnv("mock", process.cwd(), "");
  const processEnvValues = {
    "process.env": Object.entries(env).reduce((prev, [key, val]) => {
      console.log(key, val);
      return {
        ...prev,
        [key]: val,
      };
    }, {}),
  };

  return {
    plugins: [react()],
    define: processEnvValues,
  };
});

How to TEST:

1.- Add these variables to a new .env or .env.local file

REACT_APP_MAILCHIMP_URL="https://gmail.xxxx.com/subscribe/post"
REACT_APP_MAILCHIMP_U="xxxxxxxxxxxxxxxxx"
REACT_APP_MAILCHIMP_ID="YYYYYYYYYYYY"

2.- Add a new component component/Test.js file

export const Test = () => {
  console.log(import.meta.env.REACT_APP_MAILCHIMP_URL); 
  console.log(import.meta.env.REACT_APP_MAILCHIMP_U); 
  console.log(import.meta.env.REACT_APP_MAILCHIMP_ID); 

  const a_var = `${process.env.REACT_APP_MAILCHIMP_URL}`;
  console.log(a_var);

  return (

    <div>
      <small> You are running this application in mode.: 
      <b>{process.env.NODE_ENV}</b>
      </small>

      <div>
        <small> REACT_APP_NOT_SECRET_CODE:  
        <b> {process.env.REACT_APP_MAILCHIMP_URL}</b>
        </small>
      </div>
    </div>
  );
};

3.- Add Test component to App.js file

import "./App.css";

import { Test } from "./components/Test";

function App() {
  return (
    <div className="App">
      <Test />
    </div>
  );
}

export default App;
Byron2017
  • 871
  • 2
  • 11
  • 23
  • Was going to write the same thing by myself, but here you are my friend, thank you. – JEX Apr 11 '23 at 20:12
1

If you are searching for a simpler solution, you can do something like this:

import { defineConfig, loadEnv } from 'vite';

const env = loadEnv(
    'all',
    process.cwd()
);

let port = env.VITE_PORT;

The loadEnv type signature is detailed below:

function loadEnv(
  mode: string,
  envDir: string,
  prefixes: string | string[] = 'VITE_',
): Record<string, string>

By default, only env variables prefixed with VITE_ are loaded unless prefixes is changed.

Gabriele Serra
  • 381
  • 3
  • 10
0

You can use dotenv

https://github.com/motdotla/dotenv#readme

in your vite.config.js

import dotenv from 'dotenv'

dotenv.config()

process.env.YOUR_ENV_VAR 
Angus Simons
  • 528
  • 1
  • 5
  • 26