Index

no-var

需要 letconst 而不是 var

🔧 Fixable

此规则报告的一些问题可通过 --fix 命令行 选项自动修复

ECMAScript 6 允许程序员使用 letconst 关键字创建具有块级作用域而不是函数作用域的变量。块级作用域在许多其他编程语言中很常见,并有助于程序员避免以下错误:

🌐 ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the let and const keywords. Block scope is common in many other programming languages and helps programmers avoid mistakes such as:

var count = people.length;
var enoughFood = sandwiches.length >= count;

if (enoughFood) {
    var count = sandwiches.length; // accidentally overriding the count variable
    console.log("We have " + count + " sandwiches for everyone. Plenty for all!");
}

// our count variable is no longer accurate
console.log("We have " + count + " people and " + sandwiches.length + " sandwiches!");

规则详情

🌐 Rule Details

该规则旨在不鼓励使用var,而是鼓励使用constlet

🌐 This rule is aimed at discouraging the use of var and encouraging the use of const or let instead.

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

在线运行
/*eslint no-var: "error"*/

var x = "y";
var CONFIG = {};

符合此规则的正确代码示例:

🌐 Examples of correct code for this rule:

在线运行
/*eslint no-var: "error"*/

let x = "y";
const CONFIG = {};

此规则还支持 TypeScript 类型语法。在 TypeScript 中有多种声明全局变量的方式。只有使用 var 才能适用于所有情况。参考此 TypeScript playground

🌐 This rule additionally supports TypeScript type syntax. There are multiple ways to declare global variables in TypeScript. Only using var works for all cases. See this TypeScript playground for reference.

针对该规则的 错误 TypeScript 代码示例:

🌐 Examples of incorrect TypeScript code for this rule:

在线运行
/*eslint no-var: "error"*/

declare var x: number

declare namespace ns {
	var x: number
}

declare module 'module' {
	var x: number
}

针对该规则的 正确 TypeScript 代码示例:

🌐 Examples of correct TypeScript code for this rule:

在线运行
/*eslint no-var: "error"*/

declare global {
    declare var x: number
}

选项

🌐 Options

此规则没有选项。

🌐 This rule has no options.

何时不使用

🌐 When Not To Use It

除了非 ES6 环境之外,已经开始在其代码库中引入 ES6 的现有 JavaScript 项目如果从 var 迁移到 let 的成本过高,可能也不想应用此规则。

🌐 In addition to non-ES6 environments, existing JavaScript projects that are beginning to introduce ES6 into their codebase may not want to apply this rule if the cost of migrating from var to let is too costly.

版本

此规则是在 ESLint v0.12.0 中引入。

资源