or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

dotenv-webpack

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.

Package Information

  • Package Name: dotenv-webpack
  • Package Type: npm
  • Language: JavaScript (ES6 modules, transpiled to CommonJS)
  • Installation: npm install dotenv-webpack --save-dev

Core Imports

const Dotenv = require('dotenv-webpack');

For ES6 modules:

import Dotenv from 'dotenv-webpack';

Basic Usage

// 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
    })
  ]
};

Architecture

dotenv-webpack integrates with webpack's plugin system and operates through several key components:

  • Plugin Class: Main Dotenv class implementing webpack plugin interface
  • Environment Loading: Reads .env files using dotenv-defaults with support for .env.example and .env.defaults
  • Variable Processing: Handles variable expansion, interpolation, and validation
  • Bundle Integration: Uses webpack.DefinePlugin for text replacement during compilation
  • Security Features: Selective exposure and automatic process.env stubbing for browser targets

Capabilities

Plugin Construction

Creates 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'
});

Environment Variable Processing

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()

Webpack Integration

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

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
})

File Loading and Error Handling

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;
}

Process.env Stubbing

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;
}

Configuration Options

Security Options

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;
}

Variable Source Options

interface VariableSourceOptions {
  /** Path to main environment file */
  path: string;
  /** Include system environment variables */
  systemvars: boolean;
  /** Support for default values file */
  defaults: boolean | string;
}

Processing Options

interface ProcessingOptions {
  /** Enable variable expansion and interpolation */
  expand: boolean;
  /** Custom prefix for environment variables */
  prefix: string;
  /** Override automatic process.env stubbing behavior */
  ignoreStub: boolean;
}

Error Handling

The plugin handles various error conditions:

  • Missing Required Variables: When safe: true and required variables are missing, throws Error with details
  • File Loading Errors: Gracefully handles missing .env files with warnings (unless silent: true)
  • Variable Validation: Validates variables against .env.example when safe mode is enabled
  • Empty Values: Configurable handling of empty environment variables in safe mode
// Example error handling configuration
new Dotenv({
  safe: true,              // Enable validation
  allowEmptyValues: false, // Strict empty value checking
  silent: false           // Show warnings for debugging
})

Environment File Conventions

Standard Files

  • .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 Paths

// Custom file locations
new Dotenv({
  path: './config/production.env',
  safe: './config/production.env.template',
  defaults: './config/production.env.defaults'
})

Webpack Target Compatibility

The plugin automatically adapts behavior based on webpack target:

  • Browser targets: Stubs remaining process.env references to prevent errors
  • Node.js targets: Preserves process.env functionality
  • Electron main: Treats as Node.js environment
  • Universal builds: Configurable stubbing behavior via ignoreStub option

Types

/**
 * 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;
}