如何在相互依赖的 javascript 个文件组成的项目中高效使用 jshint?

How to use jshint efficiently in a project consisting of interdependent javascript files?

我是 javascript 的新手(来自 C/C++/Java),所以请多多包涵。

在我看来,linting 是一件好事。但是,我遇到了很多 "undefined variable/reference" 错误,而且我不知道如何在 'good/efficient way' 中解决该问题。

假设我有一个用 Html/Javascript 编写的更大的项目。所以我想把它拆分成相互依赖的js-modules,例如:

common_utils.js (depends on external lib d3.js)
app1.js (depends on common_utils.js)
app2.js (depends on common_utils.js as well)

首先没有办法including/referencingcommmon_utils.jsinto/toapp1.js,对吧?我只能从 html 文件中使用动态加载,对吗?

(我的意思是,这不是很奇怪吗?这似乎是最正常的事情...!!(再次强调:我来自 C++/Java))

好吧,很公平,所以 jslint/hint 无法弄清楚 common_utils.js 只会在 d3.js 加载时使用。没问题,我加

全球 d3

到我的 jshint 配置,因为一切都在 'namespace' 下。不漂亮,但还好。

但是我的 common_utils.js 呢? 我不想为该文件中的每个函数定义手动添加 linter 异常。

关于如何在 javascript 中组织和开发项目,我是不是完全搞错了?

非常感谢您的宝贵时间!

Do I get something entirely wrong about how to organize and develop projects in javascript?

不,你赚到了钱。

听起来 common_utils.js 在你的掌控之中,对吧?也就是说,这是你的代码?我假设现在是这样。


如果您发现要为每个函数添加异常,那么您就不是 namespacing,这将使 linting lots 更容易.

请注意,这就是 d3js 正在做的事情,给予或接受。这是他们网站上 d3 命名空间的 d3 使用示例:

D3 employs a declarative approach, operating on arbitrary sets of nodes called selections. For example, you can rewrite the above loop as:

d3.selectAll("p").style("color", "white");

看到那个 d3 物体了吗?你需要做同样的事情。

您应该在 common_utils.js 中声明一个 "parent" 对象并将每个函数附加到它。 那么你只需要在你的JSL/Hint设置中声明一个全局变量就可以得到全部common_util.js函数。

这里有两个快速的非 OO 示例。第一个可能是最直接的。

Note that you do need the </code> (space) between the <code>function keyword and its first parens. That is, var spam = function () is correct in JSLint and var spam = function() is not. JSLint thinks the second looks like a typical named function, not an assignment. Fair enough.

/*jslint browser: true, devel: true, sloppy: true, white: true */
var commonUtils = {};   // create the "parent" object.

// then add your functions to it, one by one.
commonUtils.test1 = function (myString) {
    if (console.log) { console.log("myString is: " + myString); }
};

commonUtils.test2 = function (myString) {
    window.alert("myString is: " + myString);
};

... 或者——我认为这更常见一些——你可以使用 JSON 表示法,一旦你理解了上面的例子,它就很容易理解:

/*jslint browser: true, devel: true, sloppy: true, white: true */
var commonUtils = {
    test1: function (myString)    {
        if (console.log) { console.log("myString is: " + myString); }
    },
    test2: function (myString)    {
        window.alert("myString is: " + myString);
    }
};

如果这很重要,您也可以 go full object oriented,但听起来您现在不需要这样做。命名空间应该可以解决问题。

现在你可以用这样的代码调用...

/*jslint browser: true, devel: true, sloppy: true, white: true */
/*global commonUtils */

commonUtils.test1("console write");
commonUtils.test2("alert write");

全局列表中的唯一项是 commonUtils,无论您在其命名空间中有多少函数。瞧。