PhantomJS 和 Node.js 中的require 含义完全相同,区别在于没有一个基本模块匹配。尽管两者都存在fs 模块,但它们是不同的并且不提供相同的功能。
require 在 PhantomJS 和 Node.js 中的功能相同。 CasperJS 构建在 PhantomJS 之上,并使用其 require 函数,但也对其进行了修补。使用 CasperJS,如果模块位于同一目录中,还可以使用名称为 require('module') 而不是 require('./module') 的模块。
全矩阵(file.js与执行脚本在同一目录):
|节点
| |幻影
| | |卡斯珀
| | | |更苗条
------------+---+---+---+--------
文件 | n | n |是 |是的
./文件 |是 |是 |是 |是的
文件.js | n | n | n | n
./file.js | n | n | n | n
PhantomJS 也可以像 node 一样使用特殊文件夹 node_modules 中定义的模块。它不能使用与 PhantomJS 中不存在的模块有依赖关系的实际节点模块。
可能需要的示例:
m.js(用于函数)
module.exports = function(){
return {
someKey: [1,2,3,4],
anotherKey: function(){
console.log("module exports works");
}
}
};
e.js(其他一切都为 JS)
exports.someKey = {
innerKey: [1,2,3,4]
};
exports.anotherKey = function(){
console.log("exports works");
};
a.json(任意 JSON)
[
{
"someKey": [ 1,2,3,4 ],
"anotherKey": 3
}
]
script.js
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"