dotenv-webpack is a secure webpack plugin that wraps dotenv and webpack.DefinePlugin to manage environment variables. It performs text replacement in webpack bundles for process.env references, exposing only explicitly referenced environment variables to prevent accidental exposure of sensitive data.
npm install dotenv-webpack --save-devconst Dotenv = require('dotenv-webpack');For ES6 modules:
import Dotenv from 'dotenv-webpack';// webpack.config.js
const Dotenv = require('dotenv-webpack');
module.exports = {
// ... other webpack config
plugins: [
new Dotenv()
]
};With custom configuration:
module.exports = {
plugins: [
new Dotenv({
path: './custom.env',
safe: true,
systemvars: true,
silent: false
})
]
};dotenv-webpack integrates with webpack's plugin system and operates through several key components:
Dotenv class implementing webpack plugin interfaceCreates a new dotenv-webpack plugin instance with configuration options.
/**
* The dotenv-webpack plugin constructor
* @param {DotenvOptions} config - Configuration options
* @returns {Dotenv} Plugin instance
*/
constructor(config = {})
interface DotenvOptions {
/** Path to environment variables file (default: './.env') */
path?: string;
/** Enable safe mode with .env.example validation (default: false) */
safe?: boolean | string;
/** Allow empty values in safe mode (default: false) */
allowEmptyValues?: boolean;
/** Load system environment variables (default: false) */
systemvars?: boolean;
/** Suppress warnings (default: false) */
silent?: boolean;
/** Enable variable expansion/interpolation (default: false) */
expand?: boolean;
/** Support for dotenv-defaults (default: false) */
defaults?: boolean | string;
/** Override automatic process.env stubbing (default: false) */
ignoreStub?: boolean;
/** Prefix for environment variables (default: 'process.env.') */
prefix?: string;
}Usage Examples:
// Basic usage with defaults
const plugin = new Dotenv();
// Custom configuration
const plugin = new Dotenv({
path: './config/.env',
safe: true,
systemvars: true,
expand: true,
defaults: true
});
// Safe mode with custom example file
const plugin = new Dotenv({
safe: './config/.env.template'
});Handles the core functionality of loading, validating, and processing environment variables.
/**
* Gather and validate environment variables from configured sources
* @returns {Object} Processed environment variables
*/
gatherVariables()
/**
* Initialize variables object, optionally including system vars
* @returns {Object} Empty object or process.env based on systemvars setting
*/
initializeVars()
/**
* Load environment variables and blueprint from files
* @returns {Object} Object containing env and blueprint properties
*/
getEnvs()
/**
* Load default values from defaults file
* @returns {string} File contents or empty string
*/
getDefaults()Integrates with webpack's compilation process through the plugin interface.
/**
* Webpack plugin interface method
* @param {webpack.Compiler} compiler - Webpack compiler instance
* @returns {void}
*/
apply(compiler)
/**
* Format variables for webpack DefinePlugin consumption
* @param {FormatDataOptions} options - Formatting options
* @returns {Object} Formatted variables for DefinePlugin
*/
formatData({ variables, target, version })
interface FormatDataOptions {
/** Environment variables to format */
variables: Object;
/** Webpack target */
target: string;
/** Webpack version */
version: string;
}Variable expansion allows environment variables to reference other variables within their values, enabling reusable configuration patterns. This feature is controlled by the expand option.
Usage Examples:
# .env file with variable expansion
DB_HOST=localhost
DB_PORT=5432
DATABASE_URL=postgres://user:pass@${DB_HOST}:${DB_PORT}/mydb
API_URL=https://${DB_HOST}/api// Enable expansion in plugin configuration
new Dotenv({
expand: true
})Handles file system operations with configurable error handling.
/**
* Load file contents with error handling
* @param {LoadFileOptions} options - File loading options
* @returns {string|{}} File contents as string or empty object on error
*/
loadFile({ file, silent })
/**
* Display console warning if not in silent mode
* @param {string} msg - Warning message
* @param {boolean} silent - Whether to suppress message
* @returns {void}
*/
warn(msg, silent)
interface LoadFileOptions {
/** File path to load */
file: string;
/** Whether to suppress warnings */
silent: boolean;
}Automatic handling of process.env references for browser compatibility in Webpack 5+.
/**
* Determine if process.env should be stubbed for target environment
* @param {StubbingOptions} options - Stubbing determination options
* @returns {boolean} Whether process.env should be stubbed
*/
shouldStub({ target, version })
interface StubbingOptions {
/** Webpack target or array of targets */
target: string | string[];
/** Webpack version */
version: string;
}interface SecurityOptions {
/** Validate required variables against example file */
safe: boolean | string;
/** Allow empty values when in safe mode */
allowEmptyValues: boolean;
/** Suppress all warnings and errors */
silent: boolean;
}interface VariableSourceOptions {
/** Path to main environment file */
path: string;
/** Include system environment variables */
systemvars: boolean;
/** Support for default values file */
defaults: boolean | string;
}interface ProcessingOptions {
/** Enable variable expansion and interpolation */
expand: boolean;
/** Custom prefix for environment variables */
prefix: string;
/** Override automatic process.env stubbing behavior */
ignoreStub: boolean;
}The plugin handles various error conditions:
safe: true and required variables are missing, throws Error with detailssilent: true)// Example error handling configuration
new Dotenv({
safe: true, // Enable validation
allowEmptyValues: false, // Strict empty value checking
silent: false // Show warnings for debugging
}).env: Main environment variables file.env.example: Template file for safe mode validation (when safe: true).env.defaults: Default values file (when defaults: true)// Custom file locations
new Dotenv({
path: './config/production.env',
safe: './config/production.env.template',
defaults: './config/production.env.defaults'
})The plugin automatically adapts behavior based on webpack target:
process.env references to prevent errorsprocess.env functionalityignoreStub option/**
* Main plugin class implementing webpack plugin interface
*/
class Dotenv {
constructor(config: DotenvOptions);
apply(compiler: webpack.Compiler): void;
gatherVariables(): Object;
initializeVars(): Object;
getEnvs(): { env: Object; blueprint: Object };
getDefaults(): string;
formatData(options: FormatDataOptions): Object;
shouldStub(options: StubbingOptions): boolean;
loadFile(options: LoadFileOptions): string | {};
warn(msg: string, silent: boolean): void;
}