Skip to content

Instantly share code, notes, and snippets.

@kevinconway
Forked from thomasdavis/universal-module.js
Created May 15, 2012 02:26
Show Gist options
  • Select an option

  • Save kevinconway/2698626 to your computer and use it in GitHub Desktop.

Select an option

Save kevinconway/2698626 to your computer and use it in GitHub Desktop.
Universal JavaScript Module.
(function (name, definition) {
"use strict";
// Call the definition in the current context so that it can access the
// global object in case of a browser environment.
var the_module = definition.call(this),
has_exports = typeof module !== 'undefined' && module.exports,
obj,
namespaces,
scope,
i,
package_name;
if (has_exports) { // Node.js Module
module.exports = the_module;
} else {
// Assign to common namespaces or simply the global object (window)
namespaces = name.split(".");
scope = this;
obj = scope;
for (i = 0; i < namespaces.length; i = i + 1) {
package_name = namespaces[i];
if (obj && i === namespaces.length - 1) {
obj[package_name] = the_module;
} else if (typeof obj[package_name] === "undefined") {
obj[package_name] = {};
}
obj = obj[package_name];
}
}
// Use .call(this, *args) to provide global context in strict mode.
}.call(this, 'core.plugin', function () {
"use strict";
// define your module here and return the public API
return {name: "my_plugin"};
}));
// Node.js
var myModule = require('myModule');
// window
myModule
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment