使用webpack在运行时动态地需要JS文件 [英] Require JS files dynamically on runtime using webpack

查看:169
本文介绍了使用webpack在运行时动态地需要JS文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个库从grunt / requirejs移植到webpack并偶然发现一个问题,这可能是这项努力的破坏者。

I am trying to port a library from grunt/requirejs to webpack and stumbled upon a problem, that might be a game-breaker for this endeavor.

图书馆我尝试port有一个函数,它可以加载和评估多个模块 - 基于我们从配置文件中获取的文件名 - 到我们的应用程序中。代码看起来像这样(咖啡):

The library I try to port has a function, that loads and evaluates multiple modules - based on their filenames that we get from a config file - into our app. The code looks like this (coffee):

loadModules = (arrayOfFilePaths) ->
  new Promise (resolve) ->
    require arrayOfFilePaths, (ms...) ->
      for module in ms
        module ModuleAPI
      resolve()

需要在运行时调用 require ,其行为与requireJS相同。 Webpack似乎只关心构建过程中发生的事情。

The require here needs to be called on runtime and behave like it did with requireJS. Webpack seems to only care about what happens in the "build-process".

这是webpack从根本上不关心的东西吗?如果是这样,我还可以使用requireJS吗?在运行时期间动态加载资产的好方法是什么?

Is this something that webpack fundamentally doesn't care about? If so, can I still use requireJS with it? What is a good solution to load assets dynamically during runtime?

编辑:loadModule可以加载模块,这些模块在此库的构建时间内不存在。它们将由实现我的库的应用程序提供。

edit: loadModule can load modules, that are not present on the build-time of this library. They will be provided by the app, that implements my library.

推荐答案

所以我发现我要求在运行时加载一些文件,这些文件仅在app-compile-time上可用而不是库 - 编译 - 时间用webpack是不可能的。

So I found that my requirement to have some files loaded on runtime, that are only available on "app-compile-time" and not on "library-compile-time" is not easily possible with webpack.

我将改变机制,以便我的库不再需要文件了,但需要传递所需的模块。有点告诉我,无论如何这将是更好的API。

I will change the mechanism, so that my library doesn't require the files anymore, but needs to be passed the required modules. Somewhat tells me, this is gonna be the better API anyways.

编辑澄清:

基本上,相反of:

# in my library
load = (path_to_file) ->
  (require path_to_file).do_something()

# in my app (using the 'compiled' libary)
cool_library.load("file_that_exists_in_my_app")

我这样做:

# in my library
load = (module) ->
  module.do_something()

# in my app (using the 'compiled' libary)
module = require("file_that_exists_in_my_app")
cool_library.load(module)

第一个代码在require.js中工作但在webpack中没有。

The first code worked in require.js but not in webpack.

事后我觉得在运行时加载第三方库加载文件是错误的。

In hindsight i feel its pretty wrong to have a 3rd-party-library load files at runtime anyway.

这篇关于使用webpack在运行时动态地需要JS文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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