Variables

  • To declare environment variables for Vite, create .env.<mode> files in the root of your project
    • Example:
      DB_PASSWORD=foobar
      VITE_SOME_KEY=123
    • Note the strings assigned to the variables are not quoted. Added quotes results in the quotes being included when replaced
  • Vite only has access to variables with names prefixed with VITE_
    • In the example above, Vite will have access to the VITE_SOME_KEY variable at build time but will not have access to DB_PASSWORD
  • To use the variable, reference it as a property on the object import.meta.env
    • To reference the VITE_SOME_KEY variable declared above, you would reference it like this: import.meta.env.VITE_SOME_KEY
    • Unlike other Javascript objects, you can not reference the environment variable as import.meta.env['VITE_SOME_KEY]'. These environment variables are replaced statically at build time, and only the dot syntax is replaced.
    • If you want the variable to be a string value in Javascript, you must include your own quotes.
      • Example: const key = 'import.meta.env.VITE_SOME_KEY';
  • You cannot use these environment variables in vite.config.js since it is a node script and is not built by Vite.

Modes

  • You can create arbitrary modes by creating .env files for those modes
    • Example: .env.staging creates a mode called “staging”
  • To build in a mode, run vite build --mode <mode>
    • Example: vite build --mode staging
  • Running vite build builds using the .env.production variables

Links