Modules in PhantomJS

PhantomJS has support for CommonJS modules, or as they call them, "user-defined modules". This means that if your script called main.js is in the same directory as your other script usefulScript.js you could load the second from main.js, using require in the same way that you would use when using nodejs.

However the official post announcing this new feature says that you should use exports to define your module's exposed functions, but that doesn't work. The right way to do it is to use module.exports, like this:


function a() {
    // Does a
}

function b() {
    // Does b
}

module.exports = {
    a: a,
    b: b
};

And then in main.js (which is executed with phantomjs main.js):


var useful = require('./usefulScript');
useful.a();
useful.b();

I thought you could only load npm-installed modules by referencing the module by its full path (including node_modules, and referencing the 'entry point' script directly), but a superhelpful commenter pointed out that maybe I could just require as normally. And it works! Of course, the modules should be compatible with the available modules and API calls in PhantomJS too.

First an example referencing the whole path:


var nodeThing = require('./node_modules/nodeThing/main.js');
nodeThing.doSomething();

The same could be rewritten as:


var nodeThing = require('nodeThing');
nodeThing.doSomething();

as long as there's a package.json file in the module that defines what the entry point of the nodeThing module is. For more information, here's the documentation for the package.json files.

Sorry if this seems a silly post, but I'm quite new to PhantomJS and I've been unable to find this answer anywhere else, so hoping this will help more people looking on how to include or use external scripts in their PhantomJS code.