Reflection API for UMD modules.
UMD is Universal Module Definition: a unification pattern that allows Javascript modules to work in both the AMD (e.g. requirejs) and the CommonJS (e.g. Node.js) environments. Various implementations of this pattern can be found here, here and here.
Heya suggests -- and uses internally in its libraries -- a relatively simple implementation of UMD intended to support the basic level of AMD as well as Node.js:
(typeof define=="function" && define
||
function(d,f,m){
m={ module:module, require:require};
module.exports=f.apply( null, d.map(
function(n){ return m[n] || require(n) }
))
}
)
It takes place of the simple define
in AMD and, when compacted into a single line of code, can be easily replaced by an optimizer tool when preparing
a build for browser-based AMD loader.
This library provides a simple reflection API that UMD modules can use to determine the environment they've been loaded into and some of its properties.
If you plan to use heya-umd
in your node.js project install it
like this:
npm install heya-umd
For your browser-based projects I suggest using volo.js:
volo install heya/umd heya-umd
Module heya/umd/umd
provides the following properties and functions:
A simple property set to an implementation dependent truthy value when loaded in AMD environment. It could, but is not guaranteed to, be a string identifying the
specific AMD loader in use such as "requirejs"
.
A simple property set to an implementation dependent truthy value when loaded in CommonJS environment. It could, but is not guaranteed to, be a string identifying
the specific CommonJS loader in use such as "node"
.
A predicate function that checks whether its argument is a valid (or valid-looking, where exact determination cannot be made) require()
function provided by the
loader.
A predicate function that checks whether its argument is a valid (or valid-looking, where exact determination cannot be made) module
object provided by the
loader.
/* UMD.define */ (typeof define=="function"&&define||function(d,f,m){m={module:module,require:require};module.exports=f.apply(null,d.map(function(n){return m[n]||require(n)}))})
( [ 'module', 'require', 'heya/umd/umd' ],
function( module, require, umd ) {
var loader = typeof umd.usingAMD == "string" && umd.usingAMD ||
umd.usingAMD && "AMD" ||
typeof umd.usingCommonJS == "string" && umd.usingCommonJS ||
umd.usingCommonJS && "CommonJS" ||
"unknown";
console.log( "Loader: " + loader );
console.log( "require() is " + ( umd.isRequire( require ) ? "recognized" : "not recognized" ) );
console.log( "module is " + ( umd.isModule( module ) ? "recognized" : "not recognized" ) );
}
)