我有一个使用Webpack的应用程序,现在我想执行以下操作:
有一个包含多个资源的文件夹:
resources
├── A.json
├── B.json
└── C.json
我想动态加载其中一个:
function getResource(name, callback) {
require(['./resources' + name + '.json'], function(resource) {
callback(resource);
});
}
这对我来说很好,期望我的所有资源都捆绑到单个1.js
文件中,但是我想拆分它们并按需加载一个。
如何使用webpack进行操作?
答案 0 :(得分:1)
Have you looked at webpack's code splitting? The syntax entry
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('foo.js', function() { ... })
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 require.ensure
statement, or if/elses, or something similar:
switch
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.