vite
vite copied to clipboard
Global constant replacement doesn't work in production
Describe the bug
I'm trying to access a global constant (declared in the define section of vite.config.js) in the browser console. While I can see the declared constant in the dev mode (pnpm run dev), it's not there when running pnpm run build && pnpm run preveiw.
Reproduction
https://github.com/tatomyr/__vite-repro
Steps to reproduce
- Run
pnpm create vite. - Create
vite.config.jsin the project's root and copypaste this example: https://vitejs.dev/config/shared-options.html#define - Run
pnpm run dev, open browser, find the__APP_VERSION__constant in the console. - Run
pnpm run build && pnpm run preview, open browser, go to the console, find that__APP_VERSION__is undefined.
System Info
System:
OS: macOS 14.4.1
CPU: (8) arm64 Apple M1 Pro
Memory: 43.80 MB / 16.00 GB
Shell: 5.9 - /bin/zsh
Binaries:
Node: 20.4.0 - ~/.asdf/installs/nodejs/20.4.0/bin/node
Yarn: 3.3.0 - ~/.asdf/installs/nodejs/20.4.0/bin/yarn
npm: 9.7.2 - ~/.asdf/plugins/nodejs/shims/npm
pnpm: 8.6.0 - ~/.asdf/shims/pnpm
Browsers:
Chrome: 125.0.6422.113
Safari: 17.4.1
npmPackages:
vite: ^5.2.0 => 5.2.0
Used Package Manager
pnpm
Logs
No response
Validations
- [X] Follow our Code of Conduct
- [X] Read the Contributing Guidelines.
- [X] Read the docs.
- [X] Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
- [X] Make sure this is a Vite issue and not a framework-specific issue. For example, if it's a Vue SFC related bug, it should likely be reported to vuejs/core instead.
- [X] Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server.
- [X] The provided reproduction is a minimal reproducible example of the bug.
you're not using it in your codebase and so it will be removed on build (tree shaked)
@userquin thanks for the explanation! But this is still an issue since the app behaviour differs in dev and production modes. Here's my case. A third-party dependency relies on a specific browser env variable and it was there during development. However, when deployed to production, the browser variable is no longer defined and the third-party code behaves differently. For me it was quite a challenge to figure out what was wrong. At least, this is something worth mentioning in the docs.
I think this is working as expected too. The documentation already clarifies this:
Define global constant replacements. Entries will be defined as globals during dev and statically replaced during build.