I'm trying to write a javascript module that I can load:
I got it almost right I believe, but I'm not sure the way it should work in node.js as I didn't use it much.
The goal:
More specifically, I would like to create a namespace named "myns":
Code looks like this:
myns-before.js:
(function(exports) {
exports.before = "myns before";
if (typeof define === 'function' && define.amd) {
define('myns-before', exports);
}
})(typeof exports !== 'undefined' ? exports : this['myns'] = this['myns'] || {});
myns.js:
(function(exports) {
exports.hello = "Hello myns";
if (typeof define === 'function' && define.amd) {
define('myns', exports);
}
})(typeof exports !== 'undefined' ? exports : this['myns'] = this['myns'] || {});
myns-after.js:
(function(exports) {
exports.after = "myns after";
if (typeof define === 'function' && define.amd) {
define('myns-after', exports);
}
})(typeof exports !== 'undefined' ? exports : this['myns'] = this['myns'] || {});
Then I would these 3 scripts differently.
1. In a normal browser:
<body>
<script src="myns-before.js"></script>
<script src="myns.js"></script>
<script src="myns-after.js"></script>
<script>
console.log("myns before:", myns, myns.before);
console.log("myns:", myns, myns.hello);
console.log("myns after:", myns, myns.after);
</script>
</body>
2. In a browser as a AMD module:
<body>
<script src="libs/require.js"></script>
<script>
require(["myns-before", "myns", "myns-after"], function(myns){
console.log("myns before:", myns, myns.before);
console.log("myns:", myns, myns.hello);
console.log("myns after:", myns, myns.after);
});
</script>
</body>
3. In node.js:
var myns1 = require('./browsers/myns-before');
var myns2 = require('./browsers/myns');
var myns3 = require('./browsers/myns-after');
console.log(">", myns1, myns1.before, myns1.hello, myns1.after);
console.log(">", myns2, myns2.before, myns2.hello, myns2.after);
console.log(">", myns3, myns3.before, myns3.hello, myns3.after);
So, in the first 2 cases (browser lodaed), I can output correctly: myns.before, myns.hello and myns.after
But in node.js, I didn't find a way to achieve the same thing. It seems that I can load the scripts only 1 by 1 and each one are set to a variable.
So the question is, how do I load these 3 scripts that needs to work in a browser, in node.js and be able to output my 3 properties: before, hello and after?
Any thought?