简体   繁体   English

有什么方法可以使用 webpack 在运行时加载资源?

[英]Any way to use webpack to load a resource at runtime?

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.我有一个.json 文件,其中包含我想使用典型的导入/要求语法从另一个脚本文件中引用的配置内容。 Currently I'm using webpack to resolve these dependencies and bundle them for me.目前我正在使用 webpack 来解决这些依赖关系并为我捆绑它们。 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.到目前为止,我还没有找到完全符合我需求的东西。

Example:例子:

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

console.log(myConfig.myFavoriteSetting);

In the example above I'd like to have myconfig.json resolved and loaded at runtime.在上面的示例中,我希望在运行时解析并加载myconfig.json

Possibly related questions:可能相关的问题:

I think what you want is require.ensure , webpack's code splitting.我认为你想要的是require.ensure ,webpack 的代码拆分。 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.您“确保”的模块被放入一个单独的包中,当您的“确保”在运行时执行时,webpack 运行时会自动通过 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;此时您仍然需要 require 所需的模块; .ensure just makes sure they're available. .ensure 只是确保它们可用。

Code splitting is one of webpack's major features, it lets you load only what you need at any given time.代码拆分是 webpack 的主要功能之一,它允许您在任何给定时间仅加载您需要的内容。 There's plugins etc. to optimize the multiple bundles as well.还有插件等来优化多个捆绑包。

With Webpack 2, you can use System.import.在 Webpack 2 中,您可以使用 System.import。 It uses the Promise API.它使用 Promise API。 AFAIK, currently there's no way to have async/await code run in the browser. AFAIK,目前无法在浏览器中运行异步/等待代码。 I believe Babel can only transpile async/await down to ES2015 so only the latest version of Node (v6.x) can run it.我相信 Babel 只能将 async/await 转换为 ES2015,因此只有最新版本的 Node (v6.x) 才能运行它。 I don't think browsers are capable of understanding it yet because the transpiled code uses generators.我认为浏览器还不能理解它,因为转译的代码使用了生成器。

For System.import please note that some older browsers (IE 11 and below I believe) will require you to polyfill the Promise API.对于 System.import 请注意,一些较旧的浏览器(我相信 IE 11 及以下)将要求您对 Promise API 进行 polyfill。 Check out polyfill.io for that.查看 polyfill.io。

If you REALLY want to use async/await in the browser, you might be able to do a full polyfill for ES2015.如果你真的想在浏览器中使用 async/await,你可以为 ES2015 做一个完整的 polyfill。

I had the same case with a file (config.json).我有一个文件(config.json)的情况。

I decided to copy it with Copy-Webpack-Plugin我决定用Copy-Webpack-Plugin复制它

new CopyWebpackPlugin([
    // Copy directory contents to {output}/
    { from: 'config.json' }
  ]) 

After that, my file was in the output build directory.之后,我的文件位于输出构建目录中。 I used 'externals' property to reference my file in my webpack.config file :我使用 'externals' 属性在我的 webpack.config 文件中引用我的文件:

  externals: {
    'config': "require('./config.json')"
  }

In my js file which load the config.json :在我加载 config.json 的 js 文件中:

import config from 'config'

'config' load require('./config.json) which is the one in the output build directory. 'config' load require('./config.json) 这是输出构建目录中的一个。

I know it's tricky but I didn't find another solution to my problem.我知道这很棘手,但我没有找到解决问题的其他方法。 Maybe it will help someone.也许它会帮助某人。

EDIT编辑

I had to use webpack in order to build because import config from 'config' wasn't understandable without it.我不得不使用 webpack 来构建,因为没有它就无法理解import config from 'config' That's why I replace :这就是我替换的原因:

externals: {
    './config.json': "require('./config.json')"
  }

and

var config = require('./config.json') //replace import config from 'config'

Without webpack, Javascript understand var config = require('./config.json') because it's the right path.没有 webpack,Javascript 理解var config = require('./config.json')因为它是正确的路径。

And when I build with webpack, it change by require('./config.json') when it sees './config.json', so it works当我用 webpack 构建时,当它看到 './config.json' 时,它会通过require('./config.json')改变,所以它可以工作

The behavior that I was originally looking for now seems to be described under the feature called Lazy Loading .我最初寻找的行为现在似乎在名为Lazy Loading的功能下进行了描述。 The feature leverages Dynamic Imports as a replacement for the previously used require.ensure way of importing dynamic resources.该功能利用 动态导入来替代以前使用的require.ensure导入动态资源的方式。

Since I don't have a example of my own to share here I'll leave this answer open as a Community Wiki answer for anybody else who would like to contribute one.由于我没有自己的示例可在这里分享,因此我将把这个答案作为社区 Wiki 答案开放给任何想贡献答案的人。

For Webpack 5:对于 Webpack 5:

Assume you need to load a config file at runtime.假设您需要在运行时加载配置文件。 File config.json :文件config.json

{
    "secret": "xxxccccvvvvXXXCCCVVV",
    "password": "1234567890"
}

And in your webpack.(config|common|prod|dev).js file:在你的 webpack.(config|common|prod|dev).js 文件中:

const configFile = require('./path/to/your/config.json');
const { DefinePlugin } = require('webpack');
// ...rest of imports

function getConfig() { // Maybe move to a helper directory *shrugs*
   return JSON.stringify(configFile);
}

module.exports = {
...(rest of webpack configuration)

   plugins: [
      new DefinePlugin({
         common_config: DefinePlugin.runtimeValue(getConfig, true)
      })
   ]
}

Finally, if you use eslint, add this so the compiler doesn't complain:最后,如果您使用 eslint,请添加以下内容以便编译器不会抱怨:

"globals": {
   "common_config": "readonly"
}

Now in your app, you have access to common_config at all times (no imports needed)现在在您的应用程序中,您可以随时访问common_config (无需导入)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有什么办法可以从子域加载json吗? - Is there any way to load json from a subdomain? 杰克逊-有什么方法可以避免在运行时对父实体进行序列化? - jackson - Is there any way to avoid serialization of parent entity at runtime? 有什么办法可以在两个方向上同时使用JsonManagedReference和JsonBackReference? - Is there any way to use JsonManagedReference and JsonBackReference in both directions? 有没有办法在SQL中使用json对象 - Is there any way to use json objects in SQL 有没有办法使用生成器并打开文件? - Is there any way to use generator and open a file? 有没有办法为AngularJS JSON请求使用浏览器缓存($ http / $ resource)? - Is there a way to use browser cache for AngularJS JSON requests ($http/$resource)? 有什么方法可以将变形的 json 加载到 python object 中? - is there any way where we can load deformed json into python object? 在统一为android构建游戏后,有什么方法可以加载文本 - Is ther any way to load text after building game for android in unity 有没有办法使用libgdx一次加载整个目录? - Is there any way to load an entire directory at once using libgdx? 在运行时加载JSON文件 - Load a JSON file at runtime
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM