Webpack bundle dynamic client config

2019-09-16 08:59发布

问题:

We have a node.js app bundled for production using Webpack.

Our problem is how to add dynamic configuration after you already have a bundle, without the need to re-bundle?

On the server-side, we can just use node env variables, but how can this be done for the client bundle? Specifically, we need to tell a browser module to which api server address to connect.

Having a js/json file with the configurations causes the configuration values to be injected into the bundle, and therefore can't be changed afterwards (in a comfortable manner, without open the bundle file and manually finding and replacing).

Using something like express-expose, isn't something we want, since it causes another network request to get the data, and our server address is dynamic.

node-config etc., don't work on client side

回答1:

You can make creative use of the externals option:

externals: [
    { appConfig: 'var appConfig' },
],

If you add that to your configuration you can just let your web server add a script tag with var appConfig = {"config":"value"}; somewhere before the loading of your webpack bundle, and a simple require('appConfig') will pick it up.