vite-plugin-env
raw JSON → 1.0.1 verified Mon Apr 27 auth: no javascript
A Vite plugin that injects custom environment variables into the client bundle via import.meta.env. Current stable version is 1.0.1, released with no documented release cadence. It differentiates from Vite's built-in env handling by allowing custom variables defined directly in the Vite config, rather than relying on .env files or process.env. Supports TypeScript types but its API surface is minimal. Caution: The README example contains a typo referencing 'vite-plugin-stachtml' which will cause import errors.
Common errors
error MissingPluginError: The plugin 'env' was not found or has invalid shape. ↓
cause env() not called as a function or imported incorrectly.
fix
Ensure you call env({ ... }) and import { env } from 'vite-plugin-env'.
error [vite] Internal server error: import.meta.env.MY_VAR is undefined ↓
cause Variable not defined in env plugin config.
fix
Add MY_VAR to the env({...}) object with a default value.
error Error: Cannot find module 'vite-plugin-env' ↓
cause Package not installed.
fix
Run npm install vite-plugin-env --save-dev
Warnings
gotcha The README example mistakenly imports from 'vite-plugin-stachtml' instead of 'vite-plugin-env'. ↓
fix Replace import { env } from 'vite-plugin-stachtml' with import { env } from 'vite-plugin-env'.
breaking The env function must be called as a function, not used as an object. Misuse will cause Vite to throw Plugin type error. ↓
fix Ensure env({ ... }) returns a valid Vite plugin object.
gotcha Variables set via env plugin are only available in client code, not in Node.js environment (e.g., vite.config.ts itself). ↓
fix Use process.env for server-side variables or define plugin for universal values.
gotcha Variable names must be uppercase or Vite may strip them due to security filters on import.meta.env. ↓
fix Use uppercase variable names (e.g., MY_VAR).
Install
npm install vite-plugin-env yarn add vite-plugin-env pnpm add vite-plugin-env Imports
- env wrong
import env from 'vite-plugin-env'correctimport { env } from 'vite-plugin-env' - vite-plugin-env (package) wrong
const vitePluginEnv = require('vite-plugin-env')correctconst { env } = require('vite-plugin-env') - Plugin type wrong
import { env } from 'vite-plugin-env' // no type importcorrectimport type { Plugin } from 'vite'; import { env } from 'vite-plugin-env'
Quickstart
// vite.config.ts
import { defineConfig } from 'vite';
import { env } from 'vite-plugin-env';
export default defineConfig({
plugins: [
env({
MY_CUSTOM_ENV: 'Hello from vite config',
YOUR_SECRET_KEY: process.env.YOUR_SECRET_KEY ?? ''
})
]
});
// src/index.ts
console.log(import.meta.env.MY_CUSTOM_ENV); // 'Hello from vite config'
console.log(import.meta.env.YOUR_SECRET_KEY); // value of env var or ''