Skip to content

envGuard ​

Validate environment variables before Vite build, supporting type checking, range validation, custom rules, and runtime guards.

Import Methods ​

typescript
// Submodule import (recommended)
import { envGuard } from '@meng-xi/vite-plugin/plugins/guard/env-guard'
import type { EnvGuardOptions, EnvGuardResult, EnvFailAction, RuntimeGuardMode } from '@meng-xi/vite-plugin/plugins/guard/env-guard'

// Barrel import
import { envGuard } from '@meng-xi/vite-plugin'

Quick Start ​

typescript
import { defineConfig } from 'vite'
import { envGuard } from '@meng-xi/vite-plugin'

export default defineConfig({
	plugins: [
		envGuard({
			required: {
				VITE_API_URL: { type: 'url', required: true },
				VITE_APP_TITLE: { type: 'string', minLength: 1, maxLength: 50 }
			},
			failAction: 'error'
		})
	]
})

Options ​

OptionTypeDefaultDescription
requiredRecord<string, EnvFieldRule>{}Environment variable validation rules
failAction'error' | 'warn' | 'ignore''error'Action on validation failure
runtimeGuardbooleanfalseInject runtime guard code
generateTemplatebooleantrueAuto-generate .env template file

Inherits BasePluginOptions: enabled, verbose, errorStrategy

Advanced Options ​

OptionTypeDefaultDescription
templateOutputstring'.env.template'Output path for .env template
runtimeGlobalNamestring'__ENV_GUARD__'Global variable name for runtime guard
runtimeGuardMode'console' | 'throw' | 'overlay''console'Runtime guard behavior mode
envFilesstring[]['.env', '.env.local', '.env.production', '.env.development'].env file paths to load
autoLoadEnvbooleantrueAuto-load .env files
reportOutputstring | falsefalseValidation report output path
validateBeforeBuildbooleantrueValidate before build starts
showSummarybooleantrueShow validation summary log

EnvFieldRule ​

Validation rule configuration for each environment variable.

PropertyTypeDescription
type'string' | 'number' | 'url' | 'boolean' | 'enum' | 'json' | 'semver' | 'path'Value type validation
requiredbooleanWhether the variable is required
defaultstringDefault value when missing
messagestringCustom error message on validation failure
patternRegExpRegex pattern validation
validator(value: string) => boolean | stringCustom validation function, return a string as the failure message
minValuenumberMinimum value (number type)
maxValuenumberMaximum value (number type)
minLengthnumberMinimum length (string type)
maxLengthnumberMaximum length (string type)
enumValuesstring[]Allowed enum values (enum type)

EnvFailAction ​

Action to take when validation fails:

ValueDescription
errorThrow error, abort build process
warnOutput warning log, continue build
ignoreSilently ignore, no output

RuntimeGuardMode ​

Runtime guard behavior mode:

ValueDescription
consoleOutput warning in browser console
throwThrow runtime error, prevent app startup
overlayDisplay warning banner at top of page

EnvGuardResult ​

Validation result summary object.

PropertyTypeDescription
timestampstringValidation timestamp (ISO format)
totalnumberTotal variables validated
passednumberNumber of passed variables
missingnumberNumber of missing required variables
invalidnumberNumber of invalid variables
resultsEnvValidationResult[]Detailed validation results
allPassedbooleanWhether all variables passed

Examples ​

Basic Type Validation ​

typescript
envGuard({
	required: {
		VITE_API_BASE_URL: {
			type: 'url',
			required: true,
			message: 'API base URL must be a valid URL'
		},
		VITE_APP_TITLE: {
			type: 'string',
			required: true,
			minLength: 1,
			maxLength: 50
		}
	}
})

Number Range and Enum Validation ​

typescript
envGuard({
	required: {
		VITE_API_TIMEOUT: {
			type: 'number',
			minValue: 1000,
			maxValue: 60000,
			message: 'API timeout must be between 1000-60000ms'
		},
		VITE_LOG_LEVEL: {
			type: 'enum',
			enumValues: ['debug', 'info', 'warn', 'error'],
			default: 'info'
		}
	}
})

Enable Runtime Guard ​

typescript
envGuard({
	required: {
		VITE_API_URL: { type: 'url', required: true }
	},
	runtimeGuard: true,
	runtimeGuardMode: 'console'
})

Generate .env Template and Validation Report ​

typescript
envGuard({
	required: {
		VITE_API_URL: { type: 'url', required: true },
		VITE_APP_TITLE: { type: 'string', required: true }
	},
	generateTemplate: true,
	templateOutput: '.env.example',
	reportOutput: 'env-guard-report.json'
})

Warn Without Breaking Build ​

typescript
envGuard({
	required: {
		VITE_ENABLE_ANALYTICS: { type: 'boolean', default: 'false' }
	},
	failAction: 'warn'
})

Notes ​

  • Validation runs in the configResolved hook, ensuring it completes before build starts
  • autoLoadEnv only loads variables starting with VITE_ by default (following Vite convention)
  • Runtime guard code is injected before the </head> tag via the transformIndexHtml hook
  • generateTemplate auto-generates a commented .env template file based on required config

Released under the MIT License.