【问题标题】:Loading webpack chunks dynamically动态加载 webpack 块
【发布时间】: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


    【解决方案1】:

    你似乎在寻找code splitting

    简而言之,您必须在代码中明确声明事物是有条件的,例如将导入(不是 es6 导入,因为它们必须在顶层,而是 CommonJS er RequireJS)包装在 if 中,或使用 require.ensure

    This 博文也可能对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-06-05
      • 2017-08-22
      • 2018-02-11
      • 2016-09-10
      • 2019-11-03
      • 2015-04-18
      • 1970-01-01
      • 2017-10-07
      相关资源
      最近更新 更多