如何在 Webpack-React 应用程序中加载外部配置文件而不捆绑它? [英] How to load an external config file in a Webpack-React application without bundling it?

查看:18
本文介绍了如何在 Webpack-React 应用程序中加载外部配置文件而不捆绑它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 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 但我现在看到的只是捆绑到 1.1.bundle.js 文件中的 config.json 的内容,而更改配置文件没有任何作用.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆