Passing environment-dependent variables in Webpack
Want to inject environment variables in Webpack? DefinePlugin is the way to go:
Simply set NODE_ENV
in your process.env
directly from your webpack config. Now you can tell apart your development from your production modes. Go ahead and use JSON.stringify
because, you know, DefinePlugin can be a bit picky. Reach your environment in your code like this: process.env.NODE_ENV
.
Going beyond the basics: Multiple environments
Sometimes, you're faced with more than just development and production - things get extra fancy. You might have staging, integration, or custom environments. And DefinePlugin is totally up for the ride.
Pick a config, any config
Your environment-specific configuration files can be set up with ease:
And your package.json
can then differ depending on the environment:
Embrace the complexity
Got complex environment variables? DefinePlugin says, "Bring it on!"
The HTML magic trick
Need to replace variables directly in your HTML? html-webpack-plugin and some creative adjustments are your best friends:
Set Sail with resolve.alias
Transitioning to webpack from gulp or similar setups? Say hello to resolve.alias. This allows for aliasing modules' identifiers and makes swapping versions feel like a breeze:
By referencing the Config
alias in your application, Webpack will redirect to the correct environment config.
Lint-friendly approach
Linting tools could get jealous with all these global constants inserted via Webpack. Pacify them by updating your ESlint configuration with the following:
Quick environment flags
For passing flags or making some minor environment-specific modifications, you can use the --env
flag in webpack directly:
It makes your webpack config a fun playground for condition-based configurations.
Was this article helpful?