如何在 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
请提出一些解决方法。
最佳答案
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.js
和 child_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.js
和 http://localhost/child_process.js
。如果由于某些原因该文件位于其他位置(例如,它是外部库),you can specify a different path .
请记住,即使您在服务器端使用 Node,您也不能只从浏览器加载 Node 模块(您似乎正在尝试这样做)。其中一些甚至在浏览器中没有意义(例如 child_process
),其他的可能作为 npm 的独立模块提供。或bower ,但我没有这方面的经验。
如果您尝试使用 RequireJS 服务器端作为 Node 的模块系统,您可以查看 relevant page .
关于javascript - 如何在 RequireJS 中为模块分配变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24971650/