Search code examples
reactjswebpackcreate-react-app

How to parameterize variables in a React Webpack app for different environments?


I'm working on a React web app which was created by create-react-app and I am getting ready to deploy it.

The issue is, for development, the app uses the api instance running on my dev environment (localhost:{api-port}) but for the deployed app this should point to the server api instance (api.myapp.com).

Currently the host is just a variable in my networking component:

const hostname = 'localhost:9876'

I plan on using webpack to generate the static files which will be served by the production front-end, and I would like to continue developing using npm start as set up by create-react-app.

What would be the correct way to set up my project such that the host can be set automatically to the correct value based on whether I'm running the dev server or building for production?


Solution

  • A common solution is to check against process.env.NODE_ENV like this:

    const hostname = process.env.NODE_ENV === "development" ? "localhost:9876" : "localhost:6789";
    

    You may need to force the environment variable to be present in your Webpack configuration file using the DefinePlugin like this:

    plugins: [
      new webpack.DefinePlugin({
        "process.env": {
          NODE_ENV:JSON.stringify(process.env.NODE_ENV || "development")
        }
      })
    ]
    

    An alternative solution might be to use the config package and provide your hostname string as a configuration parameter. config will inherit configurations from files based on the current NODE_ENV. It will start by using configuration from a default.json file, then override it with a development.json, or production.json, depending on your environment.

    Note that you'll need for the config files to be copied to your output directory using CopyWebpackPlugin for it to work.