DotenvPlugin
TheDotenvPlugin loads environment variables from .env files and makes them available during the build process. It supports multiple .env files based on the build mode and provides a flexible templating system.
This is a built-in alternative to the popular
dotenv-webpack package. It’s available in webpack 5.74.0+.Basic Usage
.env files with the WEBPACK_ prefix.
Configuration Options
Path to the directory containing .env files.Default: Project root directory
Template array for .env file names.
[mode] is replaced with the current mode.Default: [".env", ".env.local", ".env.[mode]", ".env.[mode].local"]Prefix(es) for environment variables to include.Default:
"WEBPACK_"- String: Variables must start with this prefix
- Array: Variables must start with any of these prefixes
- Function:
(key) => booleanto determine if variable should be included
Allow empty values for environment variables.
Load system environment variables.
Default values for environment variables.
File Loading Order
The plugin loads .env files in this order (later files override earlier ones):.env.env.local.env.[mode](e.g.,.env.production).env.[mode].local(e.g.,.env.production.local)
Examples
Custom Prefix
Only load variables with a specific prefix:Multiple Prefixes
Load variables with multiple prefixes:Custom Filter Function
Use a function for complete control:Mode-Specific Files
Different values for development and production: .env:--mode production, production values override defaults.
System Variables
Include system environment variables:WEBPACK_API_URL=https://api.com npm run build.
Default Values
Provide fallback values:Custom Directory
Load .env files from a specific directory:Custom Template
Use custom .env file naming:Using Loaded Variables
Variables are available throughprocess.env:
DotenvPlugin loads variables during webpack configuration. Use DefinePlugin to make them available in your application code.
Complete Example
Project structure:vs. EnvironmentPlugin
| Feature | DotenvPlugin | EnvironmentPlugin |
|---|---|---|
| Loads .env files | ✅ Yes | ❌ No |
| Mode-specific files | ✅ Yes | ❌ No |
| System env vars | Optional | ✅ Always |
| Prefix filtering | ✅ Yes | ❌ No |
| Default values | ✅ Yes | ✅ Yes |
Related
- EnvironmentPlugin - Inject system environment variables
- DefinePlugin - Define global constants
- Mode Configuration - Development vs production modes