Vite Plugin Watch Env

raw JSON →
1.0.1 verified Mon Apr 27 auth: no javascript

A Vite plugin that loads .env files into process.env and watches for file changes to automatically reload the environment. v1.0.1 is current stable. It provides two functions: loadEnv to load a .env file synchronously at config time, and watchEnv to add the Vite plugin that triggers re-serve when the .env file changes. Lightweight, TypeScript-ready, alternative to dotenv for Vite projects that need hot-reload on env changes.

error Cannot find module 'vite-plugin-watch-env'
cause Package not installed or not in devDependencies
fix
Run npm install vite-plugin-watch-env --save-dev
error TypeError: loadEnv is not a function
cause Import from wrong path or default import instead of named
fix
Use import { loadEnv } from 'vite-plugin-watch-env'
error Error: The file '.env.development' does not exist
cause File path passed to loadEnv is incorrect or file missing
fix
Ensure the path is relative to project root or absolute, and file exists
gotcha loadEnv does not merge with existing process.env – it overrides
fix Ensure to call loadEnv before any other env reads, or manually merge with Object.assign(process.env, loaded)
gotcha watchEnv only watches the path passed to loadEnv; changes to other .env files not watched
fix Call loadEnv for each .env file you want to watch
deprecated The package has no deprecation warnings, but few releases; consider using vite's built-in loadEnv for static env
fix For static env without watching, use Vite's loadEnv from 'vite' instead
npm install vite-plugin-watch-env
yarn add vite-plugin-watch-env
pnpm add vite-plugin-watch-env

Loads env file and watches for changes; exposes env to client via define.

import { defineConfig } from 'vite';
import { loadEnv, watchEnv } from 'vite-plugin-watch-env';

export default ({ mode }: { mode: string }) => {
  loadEnv(`./.env.${mode}`);
  return defineConfig({
    plugins: [watchEnv()],
    define: {
      'process.env': {
        TEST_ENV_VALUE: process.env.TEST_ENV_VALUE,
      },
    },
  });
};