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

Viewed 31707

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?

2 Answers

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: process.env.VITE_PORT,
        },
    });
}

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()],
    });
}

Related