ServerJS/Modules/SecurableModules: Difference between revisions

Line 210: Line 210:
  var a = 1;
  var a = 1;
  inc(a); // 2
  inc(a); // 2
Below is a comparison of a module written two ways.
First, the "normal" way for the browser that people are accustom to seeing these days. There are other ways to do it but this is certainly one way in an attempt to make an oranges-to-oranges comparison.
// define the library in a file called asdf.js
// first and last lines are boilerplate
var LIB=LIB||{};LIB.asdf=(function(){var exports={};
var c = 1;
exports.a = function() {return c;};
exports.b = 2;
return exports;})();
// use the library in the browser
LIB.asdf.a();
// use the library on the server
require('asdf').LIB.asdf.a();
// Use the library on the server or in browser.
// A module dependent on asdf would need to
// be written like this or something similar.
(require?require('asdf'):window).LIB.asdf.a();
Now write the library so it can be used the same way in the browser and on the server where the server has securable module loading. Note the boilerplate is about the same length and both versions of boilerplate include the name of the module. The main three lines of the library are the same.
// define the library in a file called asdf.js
// assume "exports" is not defined
// assume "modules" and "require" are defined
// first and last lines are boilerplate
var mod=function(require,exports) {
var c = 1;
exports.a = function() {return c;};
exports.b = 2;
};exports?mod(require,exports):modules['asdf']=mod;
// use the library in the browser or on the server
require('asdf').a();
39

edits