global-strict

在全局作用域内要求或禁止严格模式指令。

¥Requires or disallows strict mode directives in the global scope.

通过在代码中使用以下编译指示启用严格模式:

¥Strict mode is enabled by using the following pragma in your code:

"use strict";

当全局使用时,如本例所示,严格模式杂注适用于单个文件中的所有代码。如果在将脚本提供给浏览器之前将它们连接在一起,这可能会很危险。例如,如果你有一个在严格模式下运行的文件并将该文件与 jQuery 连接,那么严格模式现在也适用于 jQuery,并且可能会导致错误。

¥When used globally, as in this example, the strict mode pragma applies to all code within a single file. This can be dangerous if you concatenate scripts together before serving them to a browser. For instance, if you have a file running in strict mode and you concatenate that file with jQuery, the strict mode now also applies to jQuery and may cause errors.

但是,如果你使用的是 Node.js,你可能希望全局开启严格模式。在 Node.js 项目中,文件通常不会串联在一起,因此意外应用严格模式的风险很小。此外,由于 Node.js 中的每个文件都有自己的范围,全局严格模式只影响放置它的单个文件。

¥However, if you’re using Node.js, you may want to turn strict mode on globally. Files are typically not concatenated together in Node.js projects and therefore the risk of applying strict mode accidentally is minimal. Further, since every file in Node.js has its own scope, global strict mode only effects the single file in which it is placed.

规则详情

¥Rule Details

此规则要求或禁止由全局作用域内的 "use strict" pragma 调用的全局严格模式。

¥This rule requires or disallows global strict mode invoked by a "use strict" pragma in the global scope.

以下模式全局处于严格模式下,使用 "always" 选项被认为有效,使用 "never" 选项时会触发警告。

¥The following pattern is under strict mode globally and is considered valid with the "always" option and a warning with the "never" option.

"use strict";

function foo() {
    return true;
}

以下模式仅将严格模式应用于函数,因此对 "never" 选项有效,但对 "always" 选项有问题。

¥The following patterns apply strict mode only to functions so are valid with the "never" option but are problems with the "always" option.

function foo() {
    "use strict";

    return true;
}

(function() {
    "use strict";

    // other code
}());

选项

¥Options

"global-strict": ["error", "always"]

要求每个文件都有一个顶层 "use strict" 语句。

¥Requires that every file have a top-level "use strict" statement.

"global-strict": ["error", "never"]

每当在全局作用域内使用 "use strict" 时触发警告,这样它可能会污染连接的文件。

¥Warns whenever "use strict" is used in the global scope such that it could contaminate concatenated files.

何时不使用

¥When Not To Use It

当一个项目可能与严格模式代码并排使用非严格模式代码并且文件未连接时,可以根据个人情况决定使用全局严格模式,从而无需此规则。

¥When a project may use non-strict-mode code side by side with strict-mode code and the files are not concatenated, the decision to use global strict mode can be made on an individual basis, rendering this rule unnecessary.

版本

此规则是在 ESLint v0.8.0 中引入,并在 v1.0.0-rc-1 中删除。