This guide assumes you are already familiar with Webpack and how it is setup.
Today, we are going to use the DefinePlugin, included with Webpack, to define global constants and inject those into your code. With the use of NPM scripts, we can pass in an environment variable and set a specific API host URL for each environment.
Here is a simple class for sending requests to a backend:
We specify the address of our REST API and then use that in other function calls.
This is set to a local backend right now, but we have other environments, such as QA and production, that require setting this to a different backend URL. The problem we have by hardcoding the URL into our code is now we must change it every time we want to deploy code to the QA or production servers.
We can use Webpack to help us solve this problem. With DefinePlugin, we can set the API URL as a global constant and inject it into our code.
Let’s start by creating some build commands with npm. You should have a package.json similar to this already:
In the scripts section, we are going to create build commands for each environment.
First, we will create a general build command for the Webpack build process. This will run Webpack using our production config file with the progress and colors flags:
"build": "webpack --config ./webpack.production.config.js --progress --colors"
These flags will output a progress meter and use colored text while running in the terminal.
Now for each environment create a new command:
Each of these will call the regular build command, but also set the NODE_ENV variable to the specific environment we are building. This will allow the variable to be accessed in the Webpack configs.
This is our standard production Webpack config file:
In the plugins section, we are going to use the DefinePlugin and pass in a config object. Everywhere in our code where __API__ appears will be replaced with the value of apiHost:
Now, we need to write a function to define apiHost. Inside this function we have access to the the NODE_ENV variable we passed in with the npm command. Using a switch statement, we can set apiHost to the URL of our backend servers depending on the NODE_ENV. We should also set the default to our development server. The last step is to call this function.
Back in our RestService file, we can change our hardcoded server URL to __API__:
Now, each of our build commands will inject the correct server URL for deployment.