Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

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

I have a web application that is written with React and bundled with Webpack. The application has a JSON config file that I want to include at runtime and not to be bundled with webpack.

In my entry point for the application I am importing the contents using the json-loader but doing that forces the file to be embedded in the application and I can't update the config file once it's been bundled.

How can I configure my webpack.config.js file to exclude my config.json file but still let me import it in my application? It's not a module so I don't know if it can be included in the externals section of my webpack.config.js

I tried using require.ensure but all I see now is the contents of config.json bundled into a 1.1.bundle.js file and changing the config file does nothing.

app.js

let config;
require.ensure(['./config.json'], require => {
    config = require('./config.json');
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...