【问题标题】:How to assign variables to modules in RequireJS?如何为RequireJS中的模块分配变量?
【发布时间】:2014-07-26 13:45:04
【问题描述】:

如何在 RequireJS 中为模块分配变量?

换句话说,RequireJS 相当于什么:

var fs = require('fs');
var child_process = require('child_process');

我想将这些模块保存在它们各自的变量中,以便稍后调用它们的函数并处理它们。

编辑:

我尝试使用 Marco 的建议,这是我得到的错误:

Failed to load resource: the server responded with a status of 404 (Not Found) localhost/fs.js
Uncaught Error: Script error for: fs requirejs.org/docs/errors.html#scripterror

然后我将 fs.js 文件直接放在项目目录中,现在错误提示:

Uncaught Error: Module name "fs" has not been loaded yet for context: _. Use require([]) requirejs.org/docs/errors.html#notloaded
Uncaught TypeError: Cannot read property 'writeFile' of undefined

请为此提出一些解决方法。

【问题讨论】:

    标签: javascript node.js web requirejs commonjs


    【解决方案1】:

    你写的 requirejs 中的等价物是

    require(['fs','child_process'], function (fs, child_process) {
        //fs and child_process are now loaded
    });
    

    如果您需要更改导入的名称,只需更改函数参数的名称即可。

    还要记住 fs 和 child_process 的加载顺序是不能保证的。如果需要在 child_process 之前加载 fs,则需要进行两次不同的调用 o require()

    当您使用上述调用时,RequireJS 会从脚本所在的同一主机查找两个文件,fs.jschild_process.js。该路径相对于所谓的baseUrl。来自documentation

    If there is no explicit config and data-main is not used, 
    then the default baseUrl is the directory that contains 
    the HTML page running RequireJS.
    

    例如,如果您从 http://localhost/index.html 加载 RequireJS,它将查找 http://localhost/fs.jshttp://localhost/child_process.js。如果由于某些原因文件位于其他位置(例如,它是一个外部库),you can specify a different path

    请记住,即使您在服务器端使用 Node,也不能只从浏览器加载 Node 模块(看起来您正在尝试这样做)。其中一些甚至在浏览器中都没有意义(例如child_process),另一些可能作为npmbower 的独立模块提供,但我没有这方面的经验。

    如果您尝试使用 RequireJS 服务器端作为 Node 的模块系统,您可以查看relevant page

    【讨论】:

    • 感谢您的回答。我试过了,但它在 JavaScript 控制台中显示错误:“加载资源失败:服务器响应状态为 404(未找到)localhost/fs.js 未捕获错误:脚本错误:fs requirejs.org/docs/errors.html#scripterror”然后我放置了fs.js 文件在目录中,它说:“未捕获的错误:尚未为上下文加载模块名称“fs”:_。使用 require([])requirejs.org/docs/errors.html#notloaded 未捕获的类型错误:无法读取未定义的属性 'writeFile' ”。我在我的回答中粘贴了同样的评论。
    • 如果您不理解评论,请查看已编辑的问题:)
    • 我在回答中添加了更多细节,希望他们能解决您的疑问
    猜你喜欢
    • 2012-09-09
    • 2014-01-20
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    相关资源
    最近更新 更多