简体   繁体   中英

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 = {...};

I ended up throwing everything in an IIFE:

 Namespace = {}; // from another file (function() { var MyModule = (function() { return { foo: function() { console.log("bar"); } }; })(); if (typeof module !== "undefined" && module.exports) { module.exports = MyModule; } else if (typeof Namespace !== "undefined") { Namespace.MyModule = MyModule; } })(); console.log(Namespace.MyModule); 

If there is another way to do this, please, add it as an answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM