samedi 4 mars 2017

How to define a module in the browser under a namespace and in Node.js without a global variable?

I have seen this article and I know how to make a module for both the browser and Node. However, if it's been loaded in the browser, I want to save it under my namespace so that I don't pollute the global scope. The following works fine, but I leave the global Validator behind:

var Validator = (function() {
  var exports = {};

  exports.foo = function () {
    console.log("foo");
  };

  return exports;
})();

if (typeof module !== "undefined" && module.exports) {
  module.exports = Validator;
} else {
  Namespace = {}; // this has been previously defined in another file
  Namespace.Validator = Validator;
}

Namespace.Validator.foo(); // good
Validator.foo(); // bad

I tried:

(
  (typeof module !== "undefined" && module.exports)
    ? module.exports
    : Namespace.Validator
) = (function() {
  // ...
  return {};
})();

But it throws:

Uncaught ReferenceError: Invalid left-hand side in assignment


I tried:

Namespace = {}; // again, this is defined in my code somewhere else

(function(module) {
  module.foo = function () {
    console.log("bar");
  };
})(
  (typeof module !== "undefined" && module.exports)
    ? module.exports
    : Namespace.Validator
);

But Namespace.Validator is undefined.

I could add Namespace.Validator = {} at the top, but then in Node.js, I would have to create Namespace.

Question

Is there a way I could properly do this without a global variable:

// In the browser:
Namespace.MyModule = {...};

// In Node.js:
module.exports = {...};

Aucun commentaire:

Enregistrer un commentaire