vite-plugin-html-env

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

A Vite plugin for rewriting HTML templates with environment variables and conditional directives. Current stable version is 1.2.8, maintained on npm. It allows replacing placeholders in HTML files with values from .env files, supports customizable prefix/suffix (default <{ }>), and offers a compiler mode with vite-if/vite-else directives. Compiler mode is enabled by default since v1.0.4, which was a breaking change from older versions. Differentiates from similar plugins by supporting import.meta.env syntax in HTML and optionally compressing output. Ships TypeScript type definitions. Minimal peer dependency on Vite.

error Cannot find module 'vite-plugin-html-env'
cause Using CommonJS require instead of import.
fix
Use import statement: import VitePluginHtmlEnv from 'vite-plugin-html-env'
error The requested module 'vite-plugin-html-env' does not provide an export named 'VitePluginHtmlEnv'
cause Using named import instead of default import.
fix
Use default import: import VitePluginHtmlEnv from 'vite-plugin-html-env'
error TypeError: VitePluginHtmlEnv is not a function
cause Forgetting to call the plugin as a function, e.g., using VitePluginHtmlEnv instead of VitePluginHtmlEnv().
fix
Add parentheses: VitePluginHtmlEnv()
breaking Compiler mode enabled by default since v1.0.4 changes behavior from older versions. Previously used <% %> prefix/suffix and no directives. New default uses <{ }> and supports vite-if/vite-else.
fix If you need the old behavior, set compiler: false and use prefix: '<%', suffix: '%>'.
deprecated Default prefix changed from '<%' to '<{' in v1.0.4. Old prefix is still supported for compatibility but may be removed in the future.
fix Update your HTML to use <{ }> instead of <% %> for new projects.
gotcha The plugin does not expose environment variables to the client; it only replaces placeholders at build time. Do not use for secrets.
fix Store sensitive data in server-side environment variables that are not prefixed with VITE_.
gotcha When using compiler mode, vite-if/vite-else directives evaluate expressions using a simple eval-like parser. Avoid complex logic that may break.
fix Use simple comparisons (===, <, >) and avoid function calls or templates in directives.
npm install vite-plugin-html-env
yarn add vite-plugin-html-env
pnpm add vite-plugin-html-env

Shows minimal setup with compiler mode, custom env prefixes, and placeholder replacement in HTML.

// vite.config.js
import { defineConfig } from 'vite';
import VitePluginHtmlEnv from 'vite-plugin-html-env';

// .env file:
// VITE_APP_TITLE=My App
// VITE_APP_HOST=example.com

// index.html:
// <title><{ VITE_APP_TITLE }></title>
// <script src="//<{ VITE_APP_HOST }>/script.js"></script>

export default defineConfig({
  plugins: [
    VitePluginHtmlEnv({
      compiler: true,
      envPrefixes: ['VITE_', 'VITE_APP_']
    })
  ]
});