有什么方法可以使用Webpack在运行时加载资源吗? [英] Any way to use webpack to load a resource at runtime?

查看:115
本文介绍了有什么方法可以使用Webpack在运行时加载资源吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.json文件,其中包含一些配置材料,我想使用典型的import/require语法从另一个脚本文件中引用这些配置材料.目前,我正在使用webpack来解决这些依赖关系并为我捆绑它们.但是,此文件我想在运行时加载,并希望可能有某种类型的加载器可以在运行时为我解析和加载此文件.到目前为止,我还没有找到完全符合我需要的东西.

I have a single .json file that contains configuration stuff that I would like to reference from another script file using the typical import/require syntax. Currently I'm using webpack to resolve these dependencies and bundle them for me. This file however I want to be loaded at runtime and was hoping that there might be some type of loader that could resolve and load this file for me at runtime. So far I haven't found anything that matches my needs exactly.

示例:

var jQuery = require('jQuery');
var sol = require('some-other-lib');
var myConfig = require('/real/production/url/myconfig.json');

console.log(myConfig.myFavoriteSetting);

在上面的示例中,我希望在运行时解析并加载myconfig.json.

In the example above I'd like to have myconfig.json resolved and loaded at runtime.

可能相关的问题:

  • how to use webpack to load CDN or external vendor javascript lib in js file, not in html file
  • Webpack - dynamic require and paths
  • Require JS files dynamically on runtime using webpack

推荐答案

我认为您想要的是

I think what you want is require.ensure, webpack's code splitting. The modules that you 'ensure' are put into a separate bundle, and when your 'ensure' executes at runtime, the webpack runtime automatically fetches the bundle via ajax. Note the callback syntax for ensure -- your callback runs when the bundle has finished loading. You still need to require the desired modules at that point; .ensure just makes sure they're available.

代码拆分是webpack的主要功能之一,它使您可以在任何给定时间仅加载所需的内容.还有插件等也可以优化多个捆绑软件.

Code splitting is one of webpack's major features, it lets you load only what you need at any given time. There's plugins etc. to optimize the multiple bundles as well.

这篇关于有什么方法可以使用Webpack在运行时加载资源吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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