Permalink
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
51 lines (39 sloc) 1.08 KB
layout title date excerpt categories
post
Creating global constants with webpack
2017-01-25 21:26:00 -4000
How to create global constants with webpack.
webpack global constants javascript

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"