I'm have written a library which primarily made to be used in the browser. Now I want to use this library with node.js too.
My library consists of multiple files like:
loremIpsum.core.js:
loremIpsum = {};
loremIpsum.a = function(){
//Important code
}
loremIpsum.b = function(){
//Important code
}
Then there are other files which are dependent on the loremIpsum because they have to use the a or b function. Like:
loremIpsum.dolor.js:
loremIpsum.dolor = loremIpsum.a();
loremIpsum.dolor.x = function(){
//Important code
}
loremIpsum.dolor.y = function(){
//Important code
}
I have no idea how I could use that code with node.js. When I would require the files like: (pretending I've assigned exports to loremIpsum)
var loremIpsum = require("loremIpsum.core.js");
require("loremIpsum.dolor.js");
The problem is that loremIpsum.dolor.js would not work because loremIpsum is not defined.
I've read about some libraries and requireJS but I would prefer not to use such a library. Is there any good approach?
While writing the question I got an idea but I is it a good idea?
loremIpsum.core.js:
loremIpsum.dolor = loremIpsum.a();
loremIpsum.load = function(w){
require("loremIpsum." + w + ".js")(this);
}
loremIpsum.dolor.x = function(){
//Important code
}
loremIpsum.dolor.y = function(){
//Important code
}
And loremIpsum.dolor.js:
var module = function(loremIpsum){
loremIpsum.dolor = loremIpsum.a();
loremIpsum.dolor.x = function(){
//Important code
}
loremIpsum.dolor.y = function(){
//Important code
}
};
if(typeof loremIpsum !== "undefined") {
module(loremIpsum)
}
exports = module;
And then in a node.js file:
var loremIpsum = require("loremIpsum.core.js");
loremIpsum.load("dolor");
I've found a solution. I don't know if there are any disadvantages of it but it works quite well.
I've written about the solution on my blog: http://www.zujab.at/2014/09/pattern-for-a-multiple-file-javascript-library-for-the-browser-and-node-js/
The main code is:
The core file contains this method:
nowClean.load = function (lang){
if(typeof require === 'undefined'){
throw "nowClean.load may only be used with node.js";
}
var path = require('path');
require(__dirname + path.sep + "nowClean." + lang + ".js")(this);
};
An "extension" file:
var nowCleanExt = function (nowClean){
nowClean.css = nowClean.create(function (code){
/* ... */
});
/* ... */
};
if(typeof nowClean !== 'undefined'){
nowCleanExt(nowClean);
}
if(typeof module !== 'undefined'){
module.exports = nowCleanExt;
}
And then in the node main script:
var nowClean = require("nowClean");
nowClean.load("css");