JavaScript module compatibility
For my latest project I wanted to make the library to be available as an AMD or NodeJS module and, as a fallback, in a global variable (e.g. when referenced directly as a script in the browser). The following wrapper provides this kind of compatibility when there are no dependencies:
(function(namespace) {
if(typeof define == "undefined") {
define = function(fn) {
var res = fn();
if(typeof exports == "undefined") {
window[namespace] = res;
} else {
module.exports = res;
}
}
};
define(function() {
// Return the module api
return {
hello : 'World'
};
});
})('MyLib');
If there is a module loader (like RequireJS) and the define function is available, it will directly use it. In NodeJS the return value of the function given to define will be used as the module exports and in a browser environment the return value will be declared as a global variable with the name passed to the anonymous wrapper function (here it is called MyLib). Explicitly returning the modules API is also refered to as the revealing module pattern.
Using AMD (e.g. RequireJS)
With the given wrapper in a file called mylib.js in the right folder:
define(['mylib'], function(MyLib) {
console.log(MyLib.hello); // -> 'World'
// Source goes here
});
Straight in the browser
Directly loading mylib.js in the browser
<script type="text/javascript" src="mylib.js"></script>
will make the library available as a global variable with the given name (_MyLib_).
With NodeJS
Require it like any other module:
var MyLib = require('mylib');
console.log(MyLib.hello); // -> 'World'
The main drawback of this method is, that it is not possible to declare dependencies but I found it to be a good solution for small libraries that run in different JavaScript environments.
Comments
blog comments powered by Disqus