0

我试图了解require.ensure()实际是如何工作的。特别是,为什么我们需要传递require给 的回调require.ensure()

1. 这有效:

module.exports = (function () {
    require.ensure([
        "./mod.js" // files that chunk will contain
    ], function(require) {
        console.log(require("./mod.js")); // returns result of mod.js
        }, 'mod'); // name of chunk file


但是,如果我将参数的名称更改requirereq

2.这不起作用:

module.exports = (function () {
    require.ensure([
        "./mod.js" // files that chunk will contain
    ], function(req) {
        console.log(req("./mod.js")); // should return result of mod.js, but doesn't
        }, 'mod'); // name of chunk file

它会抛出一个错误:

Uncaught (in promise) TypeError: Cannot read property 'call' of undefined(…)

这来自这一行:

// Execute the module function
modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

为什么示例 #2 不起作用?

4

1 回答 1

0

我不是 100% 确定,但是如果您查看文档,您会发现您不需要将 require 函数作为回调参数接收。

require.ensure(["module-a", "module-b"], function(/* this should be empty */) {
   var a = require("module-a");
   // ...
});

所以,你可能在“req”中什么也没收到——这就是它未定义的原因——你应该使用“require”,因为,嗯,那是你需要调用的函数。

于 2016-12-12T14:07:08.343 回答