requirejs-定义函数无法正确返回依赖项



我正在使用requirejs,当我使用"定义"函数定义新模块时,我看到依赖关系已解决,但对象不是我定义的模块。

>

所有模块均以AMD格式定义,设置名称,依赖项数组和函数。出口是通过返回对象完成的。

由"定义"解决的依赖项具有以下属性:导出,ID,打包和URI。如果我打电话需要函数,则依赖项设置正确。

更新:我创建了一个带有所述问题的测试示例

html:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Test</title>
    <script src="/Scripts/require.js" data-main="../Scripts/main"></script>
    <script src="/Scripts/module.js"></script>
</head>
<body>
    <div> 
    </div>
</body>
</html>

main.js:

require(["module"], function (module) {
    module.test();
});

模块:

define([], function () {
    function test() {
        return "a";
    }
    return {
        test: test
    };
});

控制台:Untuff typeError:模块。测验不是函数

发生这种情况是因为模块不是解决了真实模块,而是在具有属性的对象上:

-config {参数:null,caller:null,长度:0,名称:" config"}

-exports {id:" @r5",uri:" ../scripts/@r5.js"}

在定义函数中设置模块名称的结果相同。

注意:在示例中,@louis检测到了一个问题。一个模块不能命名为"模块"。这帮助我修复了示例,但没有解决我的真正问题。下面我描述了解决方案。

解决方案:

我的问题与名为ACE(HTML编辑器)的库有关。这是帮助我解决的链接:https://github.com/josdejong/jsoneditor/issues/173

使用您进行的编辑,现在可以诊断出该问题。不要命名任何模块 you 用名称module写下,问题将消失。

名称module是三个保留的模块名称之一:modulerequireexports。您绝不应该用这些名称命名自己的任何模块。

当您要求Requirej加载module时,它不会加载模块。相反,它只是返回一个内部结构,该结构旨在提供有关当前模块的信息。它具有诸如id之类的字段,该字段给出了当前模块ID(即模块名称)和url,它给出了加载模块的URL,等等。

好,所以阅读

属性:出口,ID,包装和URI。

我猜想,就像@louis所说的那样,OP问题中的示例不是OP(test-)项目中的示例。

定义模块时,有2种(还有很多)一般的方法。

在标题为 CommonJS的文档中解释了它们。

如果使用

定义模块
define(function(require, exports, module) {
   console.log(module);
});

然后,第三参数module确实将包含exports, id and uri

{
   config: function config()
   exports: Object {  }
   id: "js/modules/handgrip/index.js?bust=1512509846564"
   uri: "js/modules/handgrip/index.js?bust=1512509846564&bust=1512509846564"
}

为了在给定上下文中"返回"您的模块,您可以使用

export
define(function(require, exports, module) {
   // require a depedency already loaded in context
   var someDep = require('someDep1');
   module.exports = {
      // whatever this module is about ..
   }
});

仅当您用名称定义模块,然后是依赖项,如

define('thename', [ 'someDep1', 'seomDep2', 'etc..' ], function(dep1, dep2, ..) {
   // the arguments in this context are those listed in order as defined in the array (parameters)
}

您获得了预期的结果。

- 编辑后更新

在一场混乱会议中,对不起;)很明显,正如@louis所写。

moduleexportsrequire是保留单词。

以下结果相同的结果

define(['require', 'exports', 'module'], function(require, exports, module) {
  console.log(module);
});
define(function(require, exports, module) {
  console.log(module);
});

最新更新