我通常认为这是node.js脚本/模块中的第一行以及phantomJS,casperJS等。我很好奇,如果这是服务器端javascript(SSJS)的常见模式(类似于{{ 1}}在C / C ++或Java中的#include
或者它是一个像RequireJS或LabJS这样的库被调用这个包含(我还没有机会在实践中使用它)?
e.g。 import
或var http = require('http')
我很好奇这是否已成为SSJS 标准化的模式,或者每个库/工具是否调用现有函数?
请原谅问题的 n00b 维度,但我想知道其无所不在的“原因”:)
答案 0 :(得分:20)
require()
成语是称为CommonJS的规范的一部分。具体来说,该规范的那部分称为“模块”。 RequireJS只是CommonJS的一个实现(它通常是一个浏览器端实现 - 事实上,由于浏览器的异步性,它需要different approach。
如果您查看CommonJS网站上的实施列表,您将see Node.js listed。请注意,它实现了“模块”。因此,它就是它的来源 - 它非常内置。
答案 1 :(得分:8)
PhantomJS和Node.js中的require
意味着完全相同,没有任何基本模块匹配。虽然两者都存在fs
模块,但它们是不同的,并且不提供相同的功能。
require
在功能上与PhantomJS和Node.js相同。 CasperJS构建于PhantomJS之上,并使用其require
函数,但也对其进行修补。使用CasperJS,如果模块位于同一目录中,也可以要求名称为require('module')
而不是require('./module')
的模块。
完整矩阵(file.js与执行的脚本位于同一目录中):
| node | | phantom | | | casper | | | | slimer ------------+---+---+---+-------- file | n | n | y | y ./file | y | y | y | y file.js | n | n | n | n ./file.js | n | n | n | n
PhantomJS也可以像使用节点一样使用特殊文件夹node_modules
中定义的模块。它不能使用与PhantomJS中不存在的模块具有依赖关系的实际节点模块。
module.exports = function(){
return {
someKey: [1,2,3,4],
anotherKey: function(){
console.log("module exports works");
}
}
};
exports.someKey = {
innerKey: [1,2,3,4]
};
exports.anotherKey = function(){
console.log("exports works");
};
[
{
"someKey": [ 1,2,3,4 ],
"anotherKey": 3
}
]
var m = require("./m")();
m.anotherKey(); // prints "module exports works"
var e = require("./e");
e.anotherKey(); // prints "exports works"
var a = require("./a");
console.log(a[0].anotherKey); // prints "3"