简体   繁体   English

NPM包本地VS全局范围

[英]NPM Package local VS global scope

I've been having some issues with node, npm and trying to figure out the package structure, and I'm not very sure what to Google. 我在node,npm上遇到了一些问题,试图弄清楚包的结构,但我不太确定对Google有什么看法。 I've been trying to find a common convention when it comes to how npm packages are imported. 我一直在寻找有关如何导入npm软件包的通用约定。

I've recently been writing a small web server in Node, and I've been using HttpDispatcher to help take care of requests. 我最近在Node中编写了一个小型Web服务器,并且一直在使用HttpDispatcher来帮助处理请求。 The problem comes in when I attempt to make more than one HttpDispatcher 'object.' 当我尝试制作多个HttpDispatcher“对象”时,就会出现问题。 When I do, it doesn't actually create a new one, and instead continues to use the first one I create. 当我这样做时,它实际上并没有创建一个新的,而是继续使用我创建的第一个。

I'm fairly new to Javascript and Node in general, however I have run into issues in the past where creating anonymous functions (I think that's what they're called) within a loop does not always, if at all, do as intended. 我一般对Javascript和Node还是陌生的,但是过去我遇到过这样的问题:在循环中创建匿名函数(我认为这就是它们的名字)并不总是(如果有的话)按预期进行。 Thus, I'm really curious how packages that are meant to have multiple instances are generally used? 因此,我真的很好奇通常如何使用具有多个实例的程序包?

I fixed my problem by making the HttpDispatcher 'object' global (removing the var keyword in front. This will actually create a new object as expected. I'm worried that this is not proper, though. 我通过使HttpDispatcher'object'成为全局对象(删除了前面的var关键字)解决了我的问题。这实际上将按预期方式创建一个新对象。不过,我担心这样做不合适。

So I'm asking you: What is the proper way to declare/initialize/export objects that are declared in an npm package? 所以我问你: 声明/初始化/导出在npm包中声明的对象的正确方法是什么? Should I submit a pull request or suggestion to the author of this package with my issues? 我是否应该向我的问题的软件包作者提交拉取请求或建议?

Much appreciated! 非常感激!

You're right, you should contact the author of the HttpDispatcher module 没错,您应该与HttpDispatcher模块的作者联系

At the end of the HttpDispatchermodule, instead of exporting an instance : 在HttpDispatchermodule的末尾,而不是导出实例:

module.exports = new HttpDispatcher();

The author could export the constructor itself, and then you could make as many instances as you need in consumer modules : 作者可以导出构造函数本身,然后可以在使用者模块中创建所需数量的实例:

module.exports = HttpDispatcher;

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

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