I know how to make modules in NodeJS (it’s rather simple). However, if I want to make something that is supposed to work in both server- and client-side environments, then would would one accomplish this?
Let’s imagine you want to create a Model type (“class”). Let’s say you have a class-creation function called Lib.define(). So, you write this:
Lib.Model = Lib.define({
init: function() {
// constructor...
},
save: function() {
// saves the model.
}
});
The above code would make Lib.Model an object which represents an instantiable type. However, how would you write it so that it’s also NodeJS compliant? If you try to require the above file (require('Model.js')), it would not do anything since there is no assignment to export. If, however, I do that, then am I just supposed to have a useless export object in client-side environments?
Is there other ways to do this besides require that could just simply load and parse the JS and work globally so that the above code would produce Model member in the global variable Lib?
I am looking into vm right now, but I am not sure how would I use it properly. I do have a file/class loader that resolves paths and loads scripts just like what Dojo does. Should I write some logic there that works as usual on client-side (places script tags), and for NodeJS, it would simply read the file contents and vm.runInThisContext(code)?.
JSHint just detects whether there’s an
exportssymbol and adds to it if there is. Their check looks like this:That checks to see if
exportsis an object and then checks that it’s notnull(via&& exports). Seems a reasonable approach, although of course it’s specific to the CommonJS module system (which is what Node uses).