【发布时间】:2016-01-24 07:33:06
【问题描述】:
StackOverflow 中有几个类似的问题,但我还没有真正找到答案,似乎应该是可能的。这是我想要实现的目标:
我的应用程序被 webpack 分成多个块(我使用 es6 模块)。然后在运行时我想根据需要加载块(例如:当用户导航到特定页面时,他首先需要为该页面加载 javascript 然后执行回调)。我认为这个概念是在 GWT 中开创的(但我可能错了)。
目前在 webpack 生成的 init.js 中,我看到以下代码:
/******/ // This file contains only the entry chunk.
/******/ // The chunk loading function for additional chunks
/******/ __webpack_require__.e = function requireEnsure(chunkId, callback) {
/******/ // "0" is the signal for "already loaded"
/******/ if(installedChunks[chunkId] === 0)
/******/ return callback.call(null, __webpack_require__);
/******/ // an array means "currently loading".
/******/ if(installedChunks[chunkId] !== undefined) {
/******/ installedChunks[chunkId].push(callback);
/******/ } else {
/******/ // start chunk loading
/******/ installedChunks[chunkId] = [callback];
/******/ var head = document.getElementsByTagName('head')[0];
/******/ var script = document.createElement('script');
/******/ script.type = 'text/javascript';
/******/ script.charset = 'utf-8';
/******/ script.async = true;
/******/ script.src = __webpack_require__.p + "" + chunkId + "." + ({"0":"app","1":"otherapp"}[chunkId]||chunkId) + ".js";
/******/ head.appendChild(script);
/******/ }
/******/ };
看来这正是我所需要的。但是有几个问题。首先,requireEnsure函数没有暴露给我的应用程序,第二个问题是即使我手动暴露它(通过在里面注入我的代码),它也不能像我期望的那样正确工作,因为它在.js前面加上块 ID + "."结果在获取 javascript: ..js 时重复了模块名称。这是我正在谈论的行:
script.src = __webpack_require__.p + "" + chunkId + "." + ({"0":"app","1":"otherapp"}[chunkId]||chunkId) + ".js";
有没有办法实现它?
【问题讨论】:
标签: webpack