score:2

Accepted answer

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.

score:0

there are definitely many ways you could achieve that. one of those solutions would be to use webpacks's defineplugin. in your plugins section in webpack configuration you would add something like this:

new webpack.defineplugin({
  api_host: process.env.node_env === 'production'
    ? json.stringify('localhost:8080')
    : json.stringify('api.com')
}),

that creates a global variable api_host available everywhere in your codebase, which you can use. you can read more about the defineplugin here https://webpack.js.org/plugins/define-plugin/

score:0

you could use a relative path when you make any request to your api server instead of calling the full url for your app.

and for your development you could add a proxy property to your package.json file:

{
...
"proxy": {
  "/api/*": {
      "target" :"http://localhost:9876"
  }
 }
}

so whenever you make any request that prefixed with /api will be redirected to http://localhost:9876/api this is just in the development but in the production if you make a request prefixed with /api it won't be redirected it will be served normally because the proxy is just available in the dev server coming with create-react-app.


Related Query

More Query from same tag