Creating global constants with webpack


How do we create global constants (e.g., environment variables) with webpack?

First, let’s assume you have the following configuration:

// webpack.config.js

module.exports = {
    entry: './main.js',
    output: {
        path: __dirname + '/build/',
        filename: 'bundle.js'
    }
};

To define process.env.NODE_ENV, you use DefinePlugin:

// webpack.config.js

const webpack = require('webpack');

module.exports = {
    // ...
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify('production') // '"production"'
            }
        })
    ]
};

Now, you can use the global constant as the value will be replaced at compile time:

// main.js

console.log(process.env.NODE_ENV); // "production"