Diving into webpack module loader can often seem like a confusing and daunting task. Luckily, setting environment variables is rather straight forward.
At the top of your webpack.config.js file define your environment variables like so:
/** * Example Constants */ const ENV = process.env.ENV = process.env.NODE_ENV = 'development'; const API_URL = process.env.API_URL = 'http://localhost:3000'; const METADATA = { API_URL: API_URL, ENV: ENV };
Then in the plugins array use DefinePlugin method to define global variables configured at compile time:
/** * Make Webpack Constants Available Globally */ new webpack.DefinePlugin({ 'ENV': JSON.stringify(METADATA.ENV), 'API_URL': JSON.stringify(METADATA.API_URL), 'process.env': { 'ENV': JSON.stringify(METADATA.ENV), 'NODE_ENV': JSON.stringify(METADATA.ENV), 'API_URL' : JSON.stringify(METADATA.API_URL), } }),
Re-compile and now your variables will be globally available.