动态加载js、css的已有方法就是动态创建标签,请问webpack有没有方法做到需要时才动态发请求加载资源?
(本人是webpack初学者)
webpack 4 之后可以直接用
import().then(xx=>{})
甚至可以
async function () {
await import('')
}
或者纯粹的AMD形式:
require(['./a','./b'], function(a, b) {
var c = a + b;
});
webpack会自动产生动态加载代码,结果和ensure产生的是一样的
使用 require.ensure
时可以这样简写:
require.ensure([], function(require) {
var mod = require('moduleName');
});
还可以在需要时才加载某个目录下的文件:
var name = 'moduleName';
var condition = location.hash === '#test'
condition && require.ensure([], function(require) {
var mod = require('dirName/' + name);
});
webpack 生成结果
function(module, exports, __webpack_require__) {
console.log('this is from build.js');
var name = 'aaa';
var condition = location.hash === '#test';
if (condition) {
__webpack_require__.e/* nsure */(1, function (require) {
var b = __webpack_require__(2)("./" + name + '.js');
console.log(b);
});
}
}
webpackJsonp([1],[
/* 0 */,
/* 1 */,
/* 2 */
/***/ function(module, exports, __webpack_require__) {
var map = {
"./aaa.js": 3,
"./bbb.js": 4,
"./ccc.js": 5
};
function webpackContext(req) {
return __webpack_require__(webpackContextResolve(req));
};
function webpackContextResolve(req) {
return map[req] || (function() { throw new Error("Cannot find module '" + req + "'.") }());
};
webpackContext.keys = function webpackContextKeys() {
return Object.keys(map);
};
webpackContext.resolve = webpackContextResolve;
module.exports = webpackContext;
webpackContext.id = 2;
/***/ },
/* 3 */
/***/ function(module, exports) {
module.exports = 'this is from dirName/aaa.js.'
/***/ },
/* 4 */
/***/ function(module, exports) {
/***/ },
/* 5 */
/***/ function(module, exports) {
/***/ }
]);
10 回答11.7k 阅读
2 回答3.2k 阅读✓ 已解决
2 回答4.3k 阅读✓ 已解决
3 回答1.9k 阅读✓ 已解决
2 回答1.7k 阅读✓ 已解决
4 回答2.5k 阅读✓ 已解决
5 回答3.8k 阅读
这样:
参考文档:require.ensure