0

I have an application that uses Webpack and now I want to do the following:

There is a folder with several resources:

resources
 ├── A.json
 ├── B.json
 └── C.json

I would like to load one of them dynamically:

function getResource(name, callback) {
    require(['./resources' + name + '.json'], function(resource) {
        callback(resource);
    });
}

That works fine for me, expect that all my resources bundled into the single 1.js file, but I'd like to split them and load only one on demand.

How can I do it with webpack?

1 Answer 1

1

Have you looked at webpack's code splitting? The syntax require.ensure('foo.js', function() { ... }) will cause webpack to build foo.js into a separate file at compile time, and will load it on demand (via AJAX/JSONP) at runtime.

Dynamic requires are kind of an anti-pattern in webpack, though, and require.ensure only accepts static values for the module (not expressions). An easy way to get the behavior would be to set up static require.ensure calls in a switch statement, or if/elses, or something similar:

switch (someFlagYouSet) {
  case 'a':
    require.ensure('./resources/A.json', function() {...})
    break;
  case 'b':
    require.ensure('./resources/B.json', function() {...})
    break;
  ...
}

Maybe not as graceful as one would like, but dynamic requires don't really work well with static analysis and asset generation, so you get used to it. You still get your on-demand loading at runtime.

Sign up to request clarification or add additional context in comments.

3 Comments

Brendan, thank you, that gave me several bundles as I wanted. But the issue is that I can't use switch because I don't know actual names of resources. It is plugins and I'd like not to enumerate them explicitly
@just-boris Unfortunately, you can't really do this 100% in webpack, and it needs to be built w/webpack to integrate with the rest of your build. At some level I think you will need to name each file. I did solve a similar issue: I made each resource a separate entry chunk via webpack config (so named each file there), and then wrote custom logic to request them at runtime (didn't use require). Because they were entry chunks they shared the same webpack runtime and could integrate with rest of app when they were served.
Yes, I agree with you. Write a custom plugin to webpack is the only way to go

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.