How to load an external config file in a Webpack-React application without bundling it?

匆匆过客 提交于 2019-11-29 09:32:32

If your config is not so confidential, you could do this in your index.html

<script>
  var initialState = {
    config: {
      idleTime: 120,
      fetchStatusInterval: 8,
      dataPath: 'somepath.json',
    },
  };
  window.__INITIAL_STATE__ = initialState;
</script>
<script src="static/bundle.js"></script>

And in your react application get your config with

const applicationInitialState = window.__INITIAL_STATE__;
const config = applicationInitialState.config;
Ilvenis

I ended up using a modified version of that to load my script externally. My application doesn't require the config immediately so the async aspect doesn't make a difference here.

I placed this at the top of my <head> in applications entry page with a co-located config file.

<head>
    ... other scripts
    <script>
        var config= window.config|| {};
        $.getJSON('config.json', function(response) {
            config= response;
        });
    </script>
</head>
<body>
    <div id='root'/>
    <script src='dist/app.bundle.js'></script>
</body>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!