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.
Common errors
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
Warnings
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
Install
npm install vite-plugin-watch-env yarn add vite-plugin-watch-env pnpm add vite-plugin-watch-env Imports
- loadEnv wrong
import loadEnv from 'vite-plugin-watch-env'correctimport { loadEnv } from 'vite-plugin-watch-env' - watchEnv wrong
const watchEnv = require('vite-plugin-watch-env').watchEnvcorrectimport { watchEnv } from 'vite-plugin-watch-env' - default import wrong
import { default } from 'vite-plugin-watch-env'correctimport vitePluginWatchEnv from 'vite-plugin-watch-env' - type imports wrong
import { WatchEnvOptions } from 'vite-plugin-watch-env'correctimport type { WatchEnvOptions } from 'vite-plugin-watch-env'
Quickstart
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,
},
},
});
};