Skip to content

Instantly share code, notes, and snippets.

@spiralx
Last active February 11, 2024 22:56
Show Gist options
  • Select an option

  • Save spiralx/a895fd2bcb0849c5eba2 to your computer and use it in GitHub Desktop.

Select an option

Save spiralx/a895fd2bcb0849c5eba2 to your computer and use it in GitHub Desktop.
Universal Module Definition example - AMD, CommonJS and browser support in the same file
<!DOCTYPE html>
<html>
<head>
<title>AMD/CommonJS/Browser Module Wrapper Demo</title>
</head>
<body>
<h1>AMD/CommonJS/Browser Module Wrapper Demo</h1>
<p>Module core.plugins not loaded</p>
<script src="up.js"></script>
<script>
window.onload = function() {
document.querySelector('p').innerHTML = 'Loaded <b>' +
core.plugin.config.name +
'</b>: version ' +
core.plugin.config.version;
core.plugin.foo('core.plugin.foo() has been called!');
}
</script>
</body>
</html>
'use strict';
var umdExample = require('./umd-example');
umdExample.foo('Loaded ' + umdExample.config.name + ' version ' + umdExample.config.version);
;(function(name, definition) {
var moduleObj = definition();
// AMD Module
if (typeof define === 'function') {
define(moduleObj);
}
// CommonJS Module
else if (typeof module !== 'undefined' && module.exports) {
module.exports = moduleObj;
}
// Assign to the global object (window)
else {
// account for for flat-file/global module extensions
var scopes = name.split(".");
scopes.reduce(function(scope, name, i) {
if (i === scopes.length - 1) {
scope[name] = moduleObj;
}
else if (!scope.hasOwnProperty(name)) {
scope[name] = {};
}
return scope[name];
}, this);
}
})('core.plugin', function() {
'use strict';
return {
foo: function(bar) {
console.warn(bar);
},
config: {
name: 'foo module',
version: 2
}
};
});
@spiralx
Copy link
Author

spiralx commented Aug 22, 2014

Allows you to use a single source file in a web page using the <script> tag, a CommonJS module for use with Node.js and an AMD module for require.js.

See Addy Osmani's article for an in-depth look at JavaScript modules:

http://addyosmani.com/writing-modular-js/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment