This article goes over how to create global constants (environment variables) with Webpack.
Prerequisites
Let’s assume you have the webpack config:
// webpack.config.js
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
},
};
DefinePlugin
To define process.env.NODE_ENV
, use DefinePlugin:
// webpack.config.js
const { DefinePlugin } = require('webpack');
module.exports = {
// ...
plugins: [
new DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
],
};
The global constant will be injected at compile time:
// src/index.js
console.log(process.env.NODE_ENV); // "production"