Pete
Pete

Reputation: 668

Accessing dotenv (.env) variables and build mode in Vite config

Following Vite's dotenv guide, I have been able to set up using .env variables in my project that depend on different modes (beta mode, production, etc) using different files (eg .env.beta, launching with vite ... --mode beta).

However, I would like to make some modifications to the vite.config.ts depending on these modes. For example, if I build with --mode beta I would like to change the PWA title and icon path which is instantiated in vite config as a plugin, but these are defined in vite.config.ts, which as I understand does not have access to the env variables (eg import.meta.env.VITE_BETA).

How can I get access to the build mode or env variables in vite.config.ts to change?

Upvotes: 4

Views: 10122

Answers (1)

tony19
tony19

Reputation: 138486

To add to @MichalLevy's answer of passing a function to defineConfig() for conditional config based on mode:

You can use Vite's loadEnv() to load the .env file for a specific mode:

                           👇
import { defineConfig, loadEnv } from 'vite'
import { VitePWA } from 'vite-plugin-pwa'

export default defineConfig(({ command, mode }) => {
                 👇
  const env = loadEnv(mode, process.cwd())

  const pwaTitle = `${env.VITE_PWA_TITLE ?? ''} - ${+Date.now()}`

  return {
    plugins: [
      VitePWA({
        manifest: {
          name: pwaTitle,
          â‹®
        },
      })
    ],
  }
})

demo

Upvotes: 15

Related Questions