简体   繁体   中英

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

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

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 ie bundle.js and 0.bundle.js . This 0.bundle.js has your code of config.json file.

您应该使用webpack的代码拆分功能: https ://webpack.js.org/guides/code-splitting/#src/components/Sidebar/Sidebar.jsx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM