vite icon indicating copy to clipboard operation
vite copied to clipboard

Global constant replacement doesn't work in production

Open tatomyr opened this issue 1 year ago • 2 comments

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

  1. Run pnpm create vite.
  2. Create vite.config.js in the project's root and copypaste this example: https://vitejs.dev/config/shared-options.html#define
  3. Run pnpm run dev, open browser, find the __APP_VERSION__ constant in the console.
  4. 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

tatomyr avatar May 24 '24 11:05 tatomyr

you're not using it in your codebase and so it will be removed on build (tree shaked)

userquin avatar May 24 '24 12:05 userquin

@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.

tatomyr avatar May 24 '24 13:05 tatomyr

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.

bluwy avatar May 27 '24 04:05 bluwy