Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring a userscript to use javascript modules

I'm working on a userscript - in particular this userscript - which has been designed to encapsulate functionality in modules. In order to be able to do some automated testing I would like to split the modules into their own files and use node.js's module exporting and require functions to combine into one file for use in Greasemonkey or simple browser extensions.

My first thought was to just copy the modules into their own files as such

module.js

var exportedModule = (function (){  
    var Module = {  
        // public functions and members  
    };  

    //private functions and members  

    return Module;  
}());  

module.exports = exports = exportedModule;  

And then have a central file that requires each of these modules, perhaps compiling them with something like Browserify.

script.js

var importedModule = require(./module);

importedModule.init();

Is this possible?

like image 508
cat dad Avatar asked Feb 25 '13 21:02

cat dad


1 Answers

It seems to me that you would be better off using Requirejs, which uses AMD style modules and is inherently more browser friendly. Node commonjs-style modules are synchronous and do not fit the browser model very well.

Of course, using requirejs will change your scripts a bit.

like image 158
Andrew Eisenberg Avatar answered Sep 25 '22 04:09

Andrew Eisenberg