【问题标题】:RequireJS not loading a file or module named "module.js"RequireJS 未加载名为“module.js”的文件或模块
【发布时间】:2016-01-21 14:38:11
【问题描述】:

我刚开始使用 RequireJS。我尝试了一个简单的代码,但一种方法有效,另一种无效。

文件夹“script”有“main.js”、“module.js”、“require.js”

<script data-main="script/main.js" src="script/require.js"></script>

在 main.js 中

requirejs( ['module'], function( mod ) {
    mod.sayHello();
} );

在module.js中:

define( {
    name : "value",
    sayHello : function() {
        alert( "Hello" );
    },
    sayBye : function() {
        alert( "Bye" );
    }
} );

我希望 baseUrl 是这里提到的“脚本”:

http://requirejs.org/docs/api.html#jsfiles

baseUrl 通常设置为与用于为页面加载的顶级脚本的 data-main 属性中的脚本相同的目录。

所以,我以为不会有问题,但是 mod.sayHello() 和 sayBye() 和 console.log( mod.name ) = undefined 都没有。

我尝试了console.log( mod ),它打印出如下内容:

Object {id: "_@r6", uri: "script/_@r6.js", exports: Object}

当我使用 ["script/module.js"] 而不是 ["module"] 时,console.log( mod ) 打印如下:

Object {name: "value"}
name: "value"
sayBye: ()
sayHello: ()
__proto__: Object

和 mod.sayHello()、mod.sayBye()、mod.name 都可以工作。

在main.js开头包含以下内容是一样的:

requirejs.config( {
    baseUrl: "script"
} );

我做错了什么...请帮忙。

【问题讨论】:

    标签: requirejs


    【解决方案1】:

    为您的模块使用不同于module 的名称。一方面,这是一个非常不具信息性的名称,但名为 module 的模块是 RequireJS 的一个特殊模块。它是一个提供有关您当前所在模块的信息的模块。例如,如果foo.js 包含此代码:

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

    当您请求名为foo 的模块时会加载此文件,然后console.log 将在控制台上显示"foo"

    文档没有强调module 的存在,但它在解释配置选项config 的作用时谈到了它。因为您可以通过module.config() 访问模块的配置。

    需要"script/module.js" 起作用的原因是,当你这样做时,你需要一个名为script/module.js 而不是module 的模块。

    【讨论】:

    • 哦...我刚刚发现一个名为“test.js”的文件有效(在不同的计算机上)。所以这可能是我的代码工作但不能同时工作的原因。所以,已经存在“模块”,所以它不会给我“脚本错误......找不到任何文件名”。我应该尝试使用其他文件夹中的“module.js”。这是我从未预料到的。我只阅读了 1.3 的文档,然后自己尝试了。感谢您提供这么好的信息。
    【解决方案2】:

    我继续阅读文档:

    http://requirejs.org/docs/api.html

    它导致了一个 github,其中包含有关此信息:

    https://github.com/jrburke/requirejs/wiki/Differences-between-the-simplified-CommonJS-wrapper-and-standard-AMD-define#magic

    原来“模块”和“require”、“export”一样,是一种“神奇的模块”。

    还有“模块”……:

    为您提供有关当前模块的模块 ID 和位置的信息

    https://github.com/jrburke/requirejs/wiki/Differences-between-the-simplified-CommonJS-wrapper-and-standard-AMD-define#module

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-05
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 2012-09-09
      • 1970-01-01
      相关资源
      最近更新 更多