Node.js - 为 WebStorm intellisense 声明两次 module.exports 的影响

Node.js - Impact of declaring module.exports twice for WebStorm intellisense

Sails JavaScript 应用程序中的以下声明有何影响?

var DataService = {};
module.exports = DataService;

module.exports = {
    // module code
}

我知道这是一个 "hack",它允许 WebStorm intellisense 在全局范围内识别 DataService 及其成员,但是代码在有和没有第一行的情况下是否完全相同?

谢谢!

首先,您定义一个名为 DataService 的变量,并将其等于一个空对象。之后,您将 module.exports 对象分配给 DataService 变量的值,这是一个空对象。最后,您再次使用一个空对象覆盖 module.exports 对象,但直接定义了该对象。它会有相同的行为,因为在这两种情况下,对象具有相同的数据,即一个空对象。

变量名DataService用作对本地命名空间中空对象的引用。给 module.exports 对象赋值是给它变量的数据,而不是名称。例如,当你要使用模块时,你将需要它,

var dataService = require('./data-service');

如果 DataService 是一个对象,那么您可以访问它的属性

var example = dataService.example;

但是在你的情况下,dataService直接是一个空对象,而不是DataService对象。所以你不能

var example = dataService.DataService ; 

简答:

可能(因为优化器)。

长答案:

这个可怕的 hack 可能不会在代码的运行方式上产生任何可察觉的差异。理论上,您创建一个新对象,它将占用 space 内存并花费一些 CPU 周期,但只要您不这样做,优化器很可能会简单地删除该部分代码不要在任何地方引用创建的对象(我猜...)

建议:

尝试使用 https://www.jetbrains.com/help/webstorm/2016.1/configuring-javascript-libraries.html#configure 以更稳健的方式注册您的图书馆。

An aside about intellisense in javascript

Note that this behaviour appears to be due to Webstorm not really understanding about JavaScript modules yet. For a node.js-based project, anything declared inside an imported context (like DataService.js) is scoped to that import (file), unless you explicitly export it. However, the same piece of code, running in the browser in a SCRIPT tag src file, would end up in the global context.

When you declare var DataService = {} in your application, WebStorm incorrectly assumes that you are placing the DataService variable into global scope, meaning that any other file which adds members (props/methods) to the referenced variable would end up as members of the DataService object you created.

You will note that this assumption wouldn't be strictly true, even if the variable did end up in global scope, because more than one file would declare the variable, thus overwriting the object you create in your file. JavaScript intellisense always involves a bit of guesswork because the language is very loosely typed and an object's properties can't really be determined without actually executing the code.

In general, if you declare a member in a file or against a variable named DataService somewhere in the indexed codebase, WebStorm (and most other IDEs) will bring it up as a potential member of the variable you are referencing. You can't rely on intellisense to guarantee the presence of a property through static analysis like you would in a more statically typed language like Java or C#.