Skip to content

Instantly share code, notes, and snippets.

@christianbundy
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christianbundy/37dfebe291bd5fbdebd0 to your computer and use it in GitHub Desktop.
Save christianbundy/37dfebe291bd5fbdebd0 to your computer and use it in GitHub Desktop.
Export variables to the global namespace with `module.exports` in the browser (or anywhere else). Example in the comments!
// Initialize an empty module object
module = {};
// Functions created this way don't inherit strict mode
exports = Function('return this')();
// Define what happens when you try to get or set `module.exports`
Object.defineProperty(module, 'exports', {
// Extend the top-level object with the object that's passed
set: function (obj) {
for (var prop in obj) {
// Don't set properties inherited from the prototype
if (obj.hasOwnProperty(prop)) {
exports[prop] = obj[prop];
}
}
},
// Return the top-level object
get: function () {
return exports;
}
});
@christianbundy
Copy link
Author

Let's pretend we need to export foo to the global namespace (usually window on the client and global on the server), but that our code needs to be able to run on any environment.

(function () {
  var foo = 42; // This is an awkward place to be.
}).call({});

Sure, you could probably do some typechecks, but hard coding variable references, blindly trusting your scope, and typechecking random variables are going to give you more problems than they're worth.

if (typeof window === 'object') {
  // It's a browser!
  window.foo = 42;
} else if (typeof global === 'object') {
  // It's a server!
  global.foo = 42;
} else {
  // (╯°□°)╯︵ ┻━┻
}

You could just use some JavaScript gymnastics, but nobody deserves to be subjected to this shit.

// You are not expected to understand this.
(function () { return (function() { return this; }).call(null); })().foo = 42;

Instead, just use the tried-and-true module.exports to export your local variables to the global namespace.

module.exports = {
  foo: 42 // Home sweet home.
};

It's clean, it's easy, and it's now compatible with every modern environment.

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