vite-plugin-dotenv-local
v1.0.0
Published
Vite plugin that plugs dotenv-local into Vite's config lifecycle, so env files are loaded identically in `vite dev` and `vite build`.
Maintainers
Readme
vite-plugin-dotenv-local
A Vite plugin that plugs dotenv-local into Vite's own config lifecycle (config hook), so environment variables are loaded with the exact same rules — and the exact same result — whether you run vite dev or vite build.
Why
dotenv-local's loadEnv() is a plain Node function. Calling it directly at the top of vite.config.ts only affects the Node process that evaluates the config file. It does not feed import.meta.env in client code, because that replacement is done by Vite's internal definePlugin from its own config.define — which only gets populated on vite build's final resolve step unless something wires it in for vite dev too. This plugin wires it in for both.
Install
npm install --save-dev vite-plugin-dotenv-localUsage
// vite.config.ts
import { defineConfig } from "vite";
import dotenvLocal from "vite-plugin-dotenv-local";
export default defineConfig({
plugins: [
dotenvLocal({
envPrefix: ["APP_", "SSR_"],
removeEnvPrefix: false,
}),
],
});Any variable loaded by dotenv-local becomes available in client code as:
console.log(import.meta.env.APP_DB1);identically in vite dev and in the vite build output.
Options
Accepts every LoadEnvOpts option except mode (taken from Vite's ConfigEnv) and envDir (taken from Vite's resolved envDir, overridable by passing your own), plus:
- processEnvMode:
"none" | "preserve" | "overwrite". Also syncs the loaded values intoprocess.env, sovite.config.tsitself and SSR code that readsprocess.env.Xdirectly see the same values asimport.meta.env.X. Default:"preserve". - restartOnChange:
boolean. Watches the resolved.envfiles and restarts the dev server when one changes — the same DX Vite gives its ownVITE_-prefixed env files. Default:true.
License
MIT — see LICENSE.
