如何在不捆绑Webpack-React应用程序的情况下加载外部配置文件? [英] How to load an external config file in a Webpack-React application without bundling it?
问题描述
我有一个用React编写并与Webpack捆绑在一起的Web应用程序.该应用程序具有一个JSON配置文件,我希望在运行时包含该文件,而不是将其与webpack捆绑在一起.
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.
在我的应用程序入口点中,我使用json-loader导入内容,但这会强制将文件嵌入到应用程序中,并且一旦捆绑了配置文件,我将无法更新.
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.
如何配置webpack.config.js文件以排除config.json文件,但仍允许我将其导入应用程序?它不是一个模块,所以我不知道它是否可以包含在我的webpack.config.js
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
我尝试使用require.ensure,但现在我所看到的只是将config.json的内容捆绑到1.1.bundle.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');
});
推荐答案
我最终使用了该脚本的修改版本从外部加载脚本.我的应用程序不需要立即进行配置,因此异步方面在这里没有什么不同.
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.
我将此文件放置在应用程序入口页面中<head>
的顶部,并带有一个位于同一位置的配置文件.
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>
这篇关于如何在不捆绑Webpack-React应用程序的情况下加载外部配置文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!