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 = count > sandwiches.length;

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

此规则的错误代码示例:

¥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 在线运行 以供参考。

¥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
}

何时不使用

¥When Not To Use It

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

¥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 中引入。

资源