[英]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. 我有一个用React编写并与Webpack捆绑在一起的Web应用程序。 The application has a JSON config file that I want to include at runtime and not to be bundled with webpack.
该应用程序具有一个JSON配置文件,我想在运行时将其包含在内,而不是与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. 在应用程序的入口点,我正在使用json-loader导入内容,但是这样做会强制将文件嵌入应用程序中,并且一旦捆绑了配置文件,便无法更新。
How can I configure my webpack.config.js file to exclude my config.json file but still let me import it in my application? 如何配置webpack.config.js文件以排除config.json文件,但仍允许我将其导入应用程序? It's not a module so I don't know if it can be included in the
externals
section of my webpack.config.js 它不是一个模块,所以我不知道它是否可以包含在我的webpack.config.js的
externals
部分中
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. 我尝试使用require.ensure,但现在看到的只是config.json的内容绑定到1.1.bundle.js文件中,更改配置文件无济于事。
app.js app.js
let config;
require.ensure(['./config.json'], require => {
config = require('./config.json');
});
If your config is not so confidential, you could do this in your index.html 如果您的配置不是那么机密,则可以在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 并在您的react应用程序中获取您的配置
const applicationInitialState = window.__INITIAL_STATE__;
const config = applicationInitialState.config;
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>
顶部,并带有一个位于同一位置的配置文件。
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.