I’ve been working on code that works on Browser, Web Workers and NodeJS. In order to export my module, I’ve been writing ugly code like this one:

(function () {
  /* ... Code that defines MyModule ... */
 
  var all;
  if (typeof self !== 'undefined') {
    all = self; // Web Worker
  } else if (typeof window !== 'undefined') {
    all = window; // Browser
  } else if (typeof global !== 'undefined') {
    all = global; // NodeJS
  }
  all.MyModule = MyModule;
 
  if (typeof module !== 'undefined') {
    module.exports = MyModule;
  }
})();

var all;
if (typeof self !== ‘undefined’) {
all = self; // Web Worker
} else if (typeof window !== ‘undefined’) {
all = window; // Browser
} else if (typeof global !== ‘undefined’) {
all = global; // NodeJS
}
all.MyModule = MyModule;

if (typeof module !== ‘undefined’) {
module.exports = MyModule;
}
})();

One-line Solution

Guillaume Marty showed me that sink.js uses this as a replacement for self, window and global. I managed to add support for module.exports in a one-liner!

(function (global) {
  /* ... Code that defines MyModule ... */
 
  global.MyModule = (global.module || {}).exports = MyModule;
})(this);

global.MyModule = (global.module || {}).exports = MyModule;
})(this);

I have been looking for this magic line for a long time, I hope it will be useful to you too 🙂

If you liked this article, you might be interested in my X feed as well.