React / Webpack exclude updatable configuration file from bundle

10/1/2018

My React application uses webpack to bundle the resources which are then put in a Docker image for deployment. I have a set of configuration variables that I want to add to a JSON file that can be read by my application at runtime. For example, API keys or API URLs, which can change at any time. This JSON file will be updated as and when required via Kubernetes Configmaps and Secrets.

I have looked at many posts and solutions, but none of them seem to work correctly.

For example, if I try the solutions at the below links, the JSON file gets bundled along with the other resources. I have to restart webpack / build again for the changes in the JSON file to get reflected in my application.

Webpack -- include configuration file as external resource

How to store Configuration file and read it using React

Any way to use webpack to load a resource at runtime?

What's the best way to handle my requirement?

My project structure is as follows:

├── config
│   └── jsonConfig.prod.json (This will be updated on the server)
├── src (My react application code which gets bundled via webpack)

Contents of jsonConfig.prod.json:

{
  "name": "my-app"
}

My webpack.config.js

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

In my code (after npm run build):

import * as jsonConfig from 'jsonConfig';
console.log(jsonConfig.name); // my-app

I change contents of jsonConfig.prod.json:

{
  "name": "my-app2"
}

In my code (same build as before):

import * as jsonConfig from 'jsonConfig';
console.log(jsonConfig.name); // Still my-app
-- Eric P Pereira
docker
kubernetes
reactjs
webpack

0 Answers