简体   繁体   English

如何在浏览器中的命名空间下和Node.js中定义没有全局变量的模块?

[英]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. 我看过这篇文章,并且知道如何为浏览器和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: 以下工作正常,但我将全局Validator放在后面:

 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 未捕获的ReferenceError:分配中的左侧无效


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 . 但是Namespace.Validatorundefined

I could add Namespace.Validator = {} at the top, but then in Node.js, I would have to create Namespace . 我可以在顶部添加Namespace.Validator = {} ,但是在Node.js中,我必须创建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: 我最终把所有东西都扔进了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. 如果还有另一种方法,请将其添加为答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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