How can I create a configuration file for react and prevent webpack bundling it?

827 views Asked by At

I added a config.json to application.

in webpack.config.js I defined Config

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

in application I required config and used it

var Config = require('Config');

However, webpack bundles my config file into index.js(my webpack output file) and I dont want this. I want to keep my config.json seperate from index.js To achieve this, I excluded my config.json but it did not work.

exclude: [/node_modules/, path.resolve(__dirname, 'config.dev.json'), path.resolve(__dirname, 'config.prod.json')]

Can you please help me if I miss something. Thanks

2

There are 2 answers

3
thedude On
0
iamsaksham On

As descibed by @thedude you can use webpack's code splitting feature. Instead of simply doing import config from 'config.json' you can use a really cool feature of code splitting.

require.ensure([], function(require) {
  let _config = require("config.json");
  this.setState({
    _configData: _config
  });
});

and when you want to use data of config, do that by checking state

if(this.state._configData) { // this checks _configData is not undefined as well
  // use the data of config json
}

When you will compile your code using webpack then two bundle files will be created i.e. bundle.js and 0.bundle.js. This 0.bundle.js has your code of config.json file.