Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
7 tasks done
kolorfilm opened this issue Nov 27, 2023 · 4 comments · Fixed by #15173
Closed
7 tasks done

Comments

@kolorfilm
Copy link

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

@pckilgore
Copy link

Reading the docs about how to use the esbuild define feature seemed to fix it for us:

diff --git a/src/www/vite.config.ts b/src/www/vite.config.ts
index c2a4a7f695..3e4621864d 100644
--- a/src/www/vite.config.ts
+++ b/src/www/vite.config.ts
@@ -49,19 +49,24 @@ export default defineConfig({
     }),
   ],
   define: {
-    'process.env': {
-      NODE_ENV: process.env.NODE_ENV,
-      API_ROOT: process.env.API_ROOT,
-      APP_ROOT: process.env.APP_ROOT,
-      SENTRY_ENVIRONMENT: process.env.SENTRY_ENVIRONMENT,
-
-      NEXT_PUBLIC_GOOGLE_PLACES_API_KEY:
-        process.env.NEXT_PUBLIC_GOOGLE_PLACES_API_KEY,
-      NEXT_PUBLIC_SENTRY_DSN: process.env.NEXT_PUBLIC_SENTRY_DSN,
-      NEXT_PUBLIC_SENTRY_RELEASE: process.env.NEXT_PUBLIC_SENTRY_RELEASE,
-      NEXT_PUBLIC_AMPLITUDE_ENVIRONMENT:
-        process.env.NEXT_PUBLIC_AMPLITUDE_ENVIRONMENT,
-    },
+    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
+    'process.env.API_ROOT': JSON.stringify(process.env.API_ROOT),
+    'process.env.APP_ROOT': JSON.stringify(process.env.APP_ROOT),
+    'process.env.SENTRY_ENVIRONMENT': JSON.stringify(
+      process.env.SENTRY_ENVIRONMENT
+    ),
+    'process.env.NEXT_PUBLIC_GOOGLE_PLACES_API_KEY': JSON.stringify(
+      process.env.NEXT_PUBLIC_GOOGLE_PLACES_API_KEY
+    ),
+    'process.env.NEXT_PUBLIC_SENTRY_DSN': JSON.stringify(
+      process.env.NEXT_PUBLIC_SENTRY_DSN
+    ),
+    'process.env.NEXT_PUBLIC_SENTRY_RELEASE': JSON.stringify(
+      process.env.NEXT_PUBLIC_SENTRY_RELEASE
+    ),
+    'process.env.NEXT_PUBLIC_AMPLITUDE_ENVIRONMENT': JSON.stringify(
+      process.env.NEXT_PUBLIC_AMPLITUDE_ENVIRONMENT
+    ),
   },
   resolve: {
     alias: {

@kolorfilm
Copy link
Author

kolorfilm commented Nov 28, 2023

Hi @pckilgore, thanks for your feedback and idea.

Unfortunately it doesn't work for me. When I try to use process.env in my react code on the client side process.env just is an empty object like:

console output in browser:

Bildschirmfoto 2023-11-28 um 18 16 36

I try to access the process.env variables like:

export const getEnv = (name: string): string => {
  console.log('process.env', process.env); <-- EMPTY OBJECT

  const createReactAppEnv = process.env[`REACT_APP_${name}`];

  if (!createReactAppEnv) {
    if (isRunningInTestEnvironment()) {
      return name;
    }
    throw Error(`Environment variable "${name}" is not defined.`);
  }

  return createReactAppEnv;
};

As I said when I start the application with vite (in local environment) it works. Something like vite build --mode dev and then serve the build, as it works on production, doesn't work.

I found a very interesting comment about it, but in web pack (different build approach), that basically reflects the same issue I have:

storybookjs/storybook#17336 (comment)

@kolorfilm
Copy link
Author

This approach helped me and works as a workaround for me: storybookjs/storybook#17336 (comment)

@bluwy
Copy link
Member

bluwy commented Nov 29, 2023

Yeah this seems to be an issue after Vite 5. This code:

...userDefine,
...importMetaFallbackKeys,
...(replaceProcessEnv ? processEnv : {}),

Object.assign(processEnv, {
'process.env': `{}`,
'global.process.env': `{}`,
'globalThis.process.env': `{}`,
})

Is blocking process.env from working. It worked in Vite 4 because our old replacement strategy did it this way instead.

I suppose we can fix this by moving processEnv before userDefine. This is definitely not an encouraged pattern in Vite and you should stick with import.meta.env.* instead, or plain __SOME_VAR__ keys, but I'll try a fix to see if this feasible in the meantime.

@github-actions github-actions bot locked and limited conversation to collaborators Dec 14, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants