vite: `import.meta.env.DEV` and `PROD` are incorrect if a custom `mode` is provided programmatically

Describe the bug

Ordinarily, building a Vite app results in import.meta.env.DEV === false and import.meta.env.PROD === true regardless of the mode configuration.

If you set mode when calling vite.build(...) programmatically, however, DEV and PROD are true and false unless the mode happens to be production.

Reproduction

https://github.com/Rich-Harris/vite-mode-repro

System Info

System:
    OS: macOS 12.0.1
    CPU: (10) arm64 Apple M1 Max
    Memory: 779.03 MB / 32.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 16.15.1 - ~/.nvm/versions/node/v16.15.1/bin/node
    Yarn: 1.22.19 - ~/.nvm/versions/node/v16.15.1/bin/yarn
    npm: 8.11.0 - ~/.nvm/versions/node/v16.15.1/bin/npm
  Browsers:
    Chrome: 103.0.5060.114
    Chrome Canary: 105.0.5187.0
    Firefox: 102.0.1
    Safari: 15.1
  npmPackages:
    vite: ^3.0.2 => 3.0.2

Used Package Manager

npm

Logs

No response

Validations

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 17 (12 by maintainers)

Most upvoted comments

Unfortunately no. But I think I’ve found the change (not sure it’s an issue though). We use Node workspaces but the run script, the vite config file and the .env file are on the root of the project. So vite.config.ts contains root: "./packages/application/src".

If I move the env.staging file in this folder (instead of the root of the project /), then it works again. I also tried to log VITE_SOME_KEY=123 as in the example and it works.

Hang on a sec @benmccann — it’s not working as intended. Either dev should be true in both cases where a custom mode is provided, or in neither. That’s a matter for debate — personally I think it’s bizarre that DEV is basically an alias for MODE !== 'production', and that it should instead reflect command — but either way there’s a bug here.