rendom
rendom

Reputation: 3705

Webpack React: Conditionally load json config files

I have WebPack React project which I'm testing on my "staging" server. Now its time to release it on "production" server.

I'm using server.json file which consists with server info such as api keys, api address, and so on.

What I want is to use different server.json for "production" and "staging". And when I use production-server.json, there would be no traces of staging-server.json in my bundle.

src
- config
-- config.js
-- production-server.json
-- staging-server.json

maybe something like: yarn build-staging, yarn build-production

Upvotes: 1

Views: 2067

Answers (1)

Daniel Lizik
Daniel Lizik

Reputation: 3144

You should use environment variables and webpack's DefinePlugin. Additionally, you can use node-config to automatically load a json configuration file based on your NODE_ENV.

package.json

"scripts": {
  "build:dev": "NODE_ENV=development start-something",
  "build": "NODE_ENV=production start-something"
}

project config structure

config
  default.json
    { "api": "https://api.mysite.com/v1" }
  staging.json
    { "api": "http://localhost:8000/v1" }

webpack config

// node-config will load your staging.json or default.json file here
// depending on what NODE_ENV is
const config = require('config');

plugins: [
  // inject window.CONFIG into your app
  new webpack.DefinePlugin({
    CONFIG: JSON.stringify(config)
  })
]

Then in your react code you will have access to environment-specific config

componentDidMount() {
  // in prod: https://api.mysite.com/v1/user/some-user-id
  // in staging: http://localhost:8000/v1/user/some-user-id
  return axios(`${CONFIG.api}/user/${this.props.userId}`).then(whatever...)
}

If you're on windows use cross-env to set your environment variable.

Using node-config isn't the only way to do this, there are several, but I find it pretty easy, unless you're working with electron.

edit

Since node-config uses nodejs it is typically used in front end projects in conjunction with webpack. If you are unable to to integrate it with webpack you don't need to use node-config at all, I would do something like this:

project structure

config
  default.json
  development.json
  test.json
  index.js
src
  ...etc

config files

// default.json, typically used for production
{
  "api": "https://api.mysite.com/v1"
}

// development.json
{
  "api": "http://localhost:8000/v1"
}

// index.js
// get process.env via babel-plugin-transform-inline-environment-variables
import production from './default.json';
import development from './development.json';
const { NODE_ENV: env } = process.env;

const config = {
  production,
  development
};

export default config[env];

Upvotes: 4

Related Questions