module.exports client side

17,204

Solution 1

This is what underscore.js does:

if (typeof exports !== 'undefined') {
  if (typeof module !== 'undefined' && module.exports) {
    exports = module.exports = _;
  }
  exports._ = _;
} else {
  root['_'] = _;
}

Solution 2

This answer relies on the fact that assignments are evaluated right to left. MyModule is assigned to exports first, then exports is assigned to module.exports.

If module is not declared, an exception is thrown.

Short, clean and easy to remember:

try {
   module.exports = exports = MyModule;
} catch (e) {}

This file can be included in both the browser and node.js.

Solution 3

This has worked for me (CoffeeScript). Assume 'Namespace' is what you want to claim on the window scope for the client

(module ? {}).exports = @Namespace =
  my: 'cool'
  module: '!'

Then you can use require('namespace').my === 'cool' in Node.js or Namespace.my === 'cool' in the browser. This translates into JS as

(typeof module !== "undefined" && module !== null ? module : {}).exports = this.Namespace = {
  my: 'cool',
  module: '!'
};
Share:
17,204

Related videos on Youtube

Parris
Author by

Parris

Fullstack engineer gone frontend. Currently Director of Web at Brigade. Formerly PM and Lead Frontend Engineer at Eventbrite. Focused on JS, React, GraphQL, Postgres and Build Systems. Also, familiar with WebGL, Python, (unfortunately) PHP, Go, Rust, Java and of course CSS/HTML. Current side projects: - https://github.com/fervorous/fervor - https://npmjs.org/package/iz Older projects - https://github.com/eventbrite/cartogram - https://github.com/parris/a_star.js - https://github.com/eventbrite/dorsal - https://www.npmjs.com/package/mixablejs

Updated on June 15, 2022

Comments

  • Parris
    Parris almost 2 years

    I've created a node module that is essentially just some useful JS that can also be used client side. I know that require.js can load common.js components, but I don't necessarily want to make a mandate that everyone who uses my module client side also needs require or common.js or something. I also don't want to force them to remove the module.exports = ... at the bottom of the file. How do others solve this problem? Do you just create 2 versions, or 2 "compiled" versions rather? Does module.exports work everywhere?

    • Wolfgang Kuehn
      Wolfgang Kuehn over 11 years
      The best exposition on this subject i know of is 2ality.com/2011/11/module-gap.html. The author discusses advantages/disadvantage and development/deployment modes.
  • Jun711
    Jun711 about 6 years
    I wonder how you can test this part of code to check it is exported successfully.