Skip to content

Instantly share code, notes, and snippets.

@coolaj86
Created March 5, 2012 17:39
Show Gist options
  • Save coolaj86/1979714 to your computer and use it in GitHub Desktop.
Save coolaj86/1979714 to your computer and use it in GitHub Desktop.
A module pattern for CommonJS / NodeJS and Browser / Pakmanager / RequireJS
(function (exports) {
"use strict";
exports.Foo = 'Bar';
}('undefined' !== typeof exports && exports || new Function('return this')()));
// Note: A common mistake in this pattern is to assume that `this` is the global `window`,
// but even when running in a non-strict context `this` will not be `window` when using a
// browser package manager.
// Note: This won't pass JSLint due to the implicit global `exports`, however, it will work
// even if the parent context is in strict mode also
// Note: `global.module !== module` in NodeJS or in Browser package managers
(function () {
"use strict";
var window = new Function('return this;')()
;
console.log(window.Foo);
}());
// Note: To effectively use this pattern you must nest the namespace of your module an additional level.
// So always do this:
//
// exports.ModuleName = function ModuleName() {};
// exports.ModuleName.doCoolThing = doCoolThing();
//
// But never do this:
//
// exports.doCoolThing = doCoolThing();
//
// Otherwise you'll run into browser namespace conflicts rather quickly
(function () {
"use strict";
var Foo = require('./foo').Foo
;
console.log(Foo);
}());
// Note: This pattern also works in browser package managers that understand file inclusion, such as Pakmanager
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment