Skip to content

Vite v5.0.2 | vite.config.js - config define | process.env variables on production not available anymore #15164

@kolorfilm

Description

@kolorfilm

Describe the bug

In the past I set the process.env within the vite.config.js file to can access process.env variables. I need that because I'm still using jest and need the process.env variables there as well as in cypress.

I just update to the latest version of Vite v5.0.2. I can't access the process.env variables anymore as they are empty on my production build. Locally it is still working. I think it has something to do with the changes described here.

My config looks like:

export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd(), 'REACT_APP_');
  const enableHttps = false; // set to true, if you want to use HTTPS in dev environment

  // Populate NODE_ENV with the current mode
  // dev/qa/prod = production, otherwise development
  env.NODE_ENV = mode === 'development' ? 'development' : 'production';

  const envWithProcessPrefix = {
    'process.env': `${JSON.stringify(env)}`,
  };

  const plugins = [react() as PluginOption, svgrPlugin({ include: '**/*.svg' }) as PluginOption];

  const defaultConfig = {
    plugins,
    build: {
      outDir: 'build',
    },
    define: envWithProcessPrefix,
    server: {
      port: 3000,
      open: true,
      host: true
    },
  };

  // dev config
  if (command === 'serve') {
    const servePlugins = enableHttps ? [...plugins, mkcert() as PluginOption] : [...plugins];

    return {
      ...defaultConfig,
      plugins: servePlugins,
    };
  }

  return defaultConfig;
});

The define: envWithProcessPrefix still works locally for dev but not for the production build anymore. Any ideas? Thanks!

Reproduction

https://stackblitz.com/edit/vitejs-vite-jujfte?file=vite.config.js

Steps to reproduce

vite build --mode dev

and then run the build locally

System Info

System:
    OS: macOS 14.1.1
    CPU: (8) arm64 Apple M1 Pro
    Memory: 159.98 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.10.0 - /opt/homebrew/opt/node@20/bin/node
    npm: 10.2.3 - /opt/homebrew/opt/node@20/bin/npm
  Browsers:
    Chrome: 119.0.6045.159
    Safari: 17.1
  npmPackages:
    vite: ^5.0.2 => 5.0.2

Used Package Manager

npm

Logs

No response

Validations

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions