Is 'require(...)' a common javascript pattern or a library function?

The require() idiom is part of a specification known as CommonJS. Specifically, that part of the spec is called 'Modules'. RequireJS is just one implementation of CommonJS (and it's usually a browser-side implementation - in fact, it takes a different approach because of the asynchronous nature of the browser).

If you look at the list of implementations on the CommonJS site, you'll see Node.js listed. Notice that it implements 'Modules'. Hence, that's where it's coming from - it's very much built-in.


The require in PhantomJS and Node.js means exactly the same with the difference that none of the base modules match. Although the fs module exists for both, they are different and do not provide the same functions.

require is functionally the same in PhantomJS and Node.js. CasperJS is built on top of PhantomJS and uses its require function, but also patches it. With CasperJS it is also possible to require a module with its name such as require('module') instead of require('./module') if it is in the same directory.

Full matrix (file.js is in the same directory as the executed script):

            | 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 can also use modules defined in the special folder node_modules in the same way that node does. It cannot use actual node modules that have dependencies to modules that are not present in PhantomJS.

Examples of what can be required:

m.js (for functions)

module.exports = function(){
    return {
        someKey: [1,2,3,4],
        anotherKey: function(){
            console.log("module exports works");
        }
    }
};

e.js (for everything else as JS)

exports.someKey = {
    innerKey: [1,2,3,4]
};

exports.anotherKey = function(){
    console.log("exports works");
};

a.json (arbitrary 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"