vitejs/vite-plugin-react

Env variable is being replace in build time

guidari opened this issue · 2 comments

Describe the bug

I am using this config in my main.js to make the build to work. However, I have defined a global environment variable called __DEV__ in my project, and this variable is being replaced at build time, resulting in the following error: __DEV__ is not defined.

Screenshot 2024-08-13 at 17 01 27

With that in mind, we tried to define __DEV__ in the main.js as follows:

if (configType === 'DEVELOPMENT') {
      config.define = {
        __DEV__: 'true',
      };
    }
    if (configType === 'PRODUCTION') {
      config.define = {
        __DEV__: 'false',
      };
    }

However, a new error appears:

Screenshot 2024-08-15 at 11 19 30

How do we know this is replacing __DEV__ ? We have a component called ModalWrapper that uses __DEV__ and if we comment out the line with the variable, the errors goes away.

Here it is the main.js file in the last commit with the issue

We also tried to use our existing pipeline with babel-plugin-dev-expression but it didn't work.

Possible solution:
Maybe if we can enforce the order that babel will run we can fix it?

Reproduction

carbon-design-system/carbon#16910

Steps to reproduce

I paste the PR I'm working on. You can check the error in the commit:
fix: added babel back
75cc693

Go to Checks to see the CI error in vrt-runner (4)

System Info

System:
    OS: macOS 14.6
    CPU: (10) x64 Apple M1 Pro
    Memory: 32.66 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 18.14.2 - ~/.nvm/versions/node/v18.14.2/bin/node
    Yarn: 4.2.2 - /usr/local/bin/yarn
    npm: 9.5.0 - ~/.nvm/versions/node/v18.14.2/bin/npm
    Watchman: 2023.08.07.00 - /opt/homebrew/bin/watchman
  Browsers:
    Chrome: 127.0.6533.120
    Firefox: 129.0.1
    Safari: 17.6

Used Package Manager

yarn

Logs

No response

Validations

The reproduction has many moving parts (babel, custom esbuild config + vite is mainly driven by storybook) and I don't think it's easy to spot anything quickly. We'll probably need a reproduction outside of storybook at least.

Btw from your PR, it's not clear which version of Vite and plugins you're using (or automatically installed by storybook?). Please make sure to provide the information.

I haven't tried to run your PR locally yet, but one thing I might try to debug the broken transform is to maybe add own transform to dump intermediate results, something like:

plugins: [
  {
    name: "debug-transform",
    // enforce: "pre", 
    transform(code, id) {
      if (id.includes("ModalWrapper.tsx")) console.log({ id, code })
    }
  }
]

I'm not sure if Storybook is compatible, but you might also be able to debug using https://github.com/antfu-collective/vite-plugin-inspect

Hello @guidari. Please provide a minimal reproduction using a GitHub repository or StackBlitz. Issues marked with need reproduction will be closed if they have no activity within 3 days.