Webpack Environment Variables

Managing environment variables

DefinePlugin

const webpack = require('webpack');
plugins: [
    new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify('production'),
        'API_URL': JSON.stringify('https://api.example.com')
    })
]

dotenv Plugin

npm install dotenv-webpack # install
const Dotenv = require('dotenv-webpack');
plugins: [
    new Dotenv() # load .env file
]

Environment Config

// webpack.config.js
module.exports = (env) => {
    return {
        mode: env.production ? 'production' : 'development'
    };
};
# usage
webpack --env production