ESLint的使用

ESLint是一个语法规则和代码风格的检查工具,可以用来保证写出语法正确、风格统一的代码。

首先,安装ESLint。

$ npm install -g eslint

eslint需要一个配置文件才能工作,这个配置文件可以是JavaScript/JSON/YMAL格式。

$ eslint --init
? How would you like to configure ESLint? Answer questions about your style
? Are you using ECMAScript 6 features? Yes
? Are you using ES6 modules? Yes
? Where will your code run? Browser
? Do you use CommonJS? No
? Do you use JSX? No
? What style of indentation do you use? Spaces
? What quotes do you use for strings? Single
? What line endings do you use? Unix
? Do you require semicolons? Yes
? What format do you want your config file to be in? JSON
Successfully created .eslintrc.json file in D:\htdocs\vue\webpack-simple  

如果你习惯使用当前流行的风格,请选择"Use a popular style guide"。(不推荐,建议跟着贵司走)

$ eslint --init
? How would you like to configure ESLint? Use a popular style guide
? Which style guide do you want to follow? Airbnb
? Do you use React? No
? What format do you want your config file to be in? JavaScript

现在就可以检查,当前项目的代码是否符合预设的规则。

index.js文件的代码如下。

var unusued = 'I have no purpose!';

function greet() {  
    var message = 'Hello, World!';
    alert(message);
}

greet();  

使用ESLint检查这个文件。

$ eslint index.js
index.js  
  1:5  error  unusued is defined but never used                 no-unused-vars
  4:5  error  Expected indentation of 2 characters but found 4  indent
  5:5  error  Expected indentation of 2 characters but found 4  indent

✖ 3 problems (3 errors, 0 warnings)

上面代码说明,原文件有三个错误,一个是定义了变量,却没有使用,另外两个是行首缩进为4个空格,而不是规定的2个空格。

Arvin Xiang

Read more posts by this author.

Subscribe to Arvin Xiang

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!