2

I have a React+Flux app and using Webpack. The REST API I am consuming is served by a different server and I am trying to figure out where I could specify the backend endpoint constant depending whether I am on dev or prod environments.

Currently, for dev, I have harcoded the URL to be localhost:port, but when I deploy, it still tries to access the endpoints at localhost.

It seems like it should be something pretty common, but can't find any info.

eltuza
  • 84
  • 1
  • 5
  • Possible duplicate of [How to store Configuration file and read it using React](http://stackoverflow.com/questions/30568796/how-to-store-configuration-file-and-read-it-using-react) – JulienD Feb 26 '17 at 01:25

2 Answers2

6

You can add environmental variables to your webpack scripts. A common practice for node is to use ENV=production||dev when you are using the webpack script in bash or your package.json. Next you can create two different config files, one for production and one for dev.

plugins: [
    new webpack.DefinePlugin({
        ENV: process.ENV === 'dev' ? require('./dev-config-path')) : require('./prod-config-path')
    })
]

ENV should now be attached to the window object. Make sure not to add API keys or anything since it will be accessible. You could also just hardcode the api URL.

plugins: [
    new webpack.DefinePlugin({
        API: process.ENV === 'dev' ? 'localhost:3000' : 'xxx.xxx.x.x'
    })
]
Andrew Axton
  • 1,032
  • 7
  • 9
  • 1
    Why in "plugins"? This other answers says we should use the 'external" field: http://stackoverflow.com/a/30602665/2197181. Are both approaches equivalent? – JulienD Feb 26 '17 at 01:24
0

I find it easier to use webpack's externals property on webpack.config.js. This is what you do:

In webpack.config.js

    ...
    externals: {
      config: JSON.stringify(production ? require('./config.prod.json') : require('./config.dev.json'))
    }
    ...

This way you can have separate files for different environments that lists ALL the config variables that you need. Further you could have webpack.config.dev.js and webpack.config.prod.js and specify the same externals key there and skip the ternary check.

Finally, you access them in code as a commonjs module - var config = require('config')

vijay
  • 324
  • 1
  • 4
  • 11
  • Could you print your stack trace ? – vijay May 25 '17 at 11:42
  • @ceebreenk you need to define the `externals` as a direct child of your `module.exports`. Make sure that is the case. ``` module.exports = { ... externals: {} } ``` – vijay May 25 '17 at 11:44