User refactoring to use javascript modules

I am working on usercript - in particular this usercript - which was designed to encapsulate functionality in modules. To be able to perform automatic testing, I would like to separate the modules into my own files and use the node.js module for export and require the functions to be combined into one file for use in Greasemonkey or in simple browser extensions.

My first thought was to simply copy the modules into my 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 you have a central file that requires each of these modules, maybe compile them with something like Browserify .

script.js

 var importedModule = require(./module); importedModule.init(); 

Is it possible?

+4
source share
2 answers

It seems to me that you are better off using Requirejs , which uses AMD-style modules and is essentially a friendlier browser. The commonjs-style Node modules are synchronous and not well suited to the browser model.

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

+2
source

It is possible, and Browserify makes it easy:

 browserify src/my.user.js -o dist/my.user.js 

Metadata in the source file can be moved, but it is still parsed correctly (at least Greasemonkey).

For a more complex example that collects various resources, including CSS and images, see here .

+1
source

All Articles