Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

javascript - Require JS files dynamically on runtime using 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.

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()

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".

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?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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.

edit to clarify:

Basically, instead 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")

I do this:

# 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)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...