介绍
ESLint 是一个插件化的 javascript 代码检测工具,它可以用于检查常见的 JavaScript 代码错误,也可以进行代码风格检查,这样我们就可以根据自己的喜好指定一套 ESLint 配置,然后应用到所编写的项目上,从而实现辅助编码规范的执行,有效控制项目代码的质量。
安装
ESLint的安装:本地安装、全局安装
1、本地安装
$ npm install eslint --save-dev
生成配置文件
$ ./node_modules/.bin/eslint --init
之后,您可以运行ESLint在任何文件或目录如下:
$ ./node_modules/.bin/eslint index.js
index.js是你需要测试的js文件。你使用的任何插件或共享配置(必须安装在本地来与安装在本地的ESLint一起工作)。
2、全局安装
如果你想让ESLint可用到所有的项目,建议全局安装ESLint。
$ npm install -g eslint
生成配置文件
$ eslint --init
之后,您可以在任何文件或目录运行ESLint
$ eslint index.js
PS:eslint --init是用于每一个项目设置和配置eslint,并将执行本地安装的ESLint及其插件的目录。如果你喜欢使用全局安装的ESLint,在你配置中使用的任何插件都必须是全局安装的。
使用
1、在项目根目录生成package.json文件(配置ESLint的项目中必须有 package.json 文件,如果没有的话可以使用 npm init -y来生成)
$ npm init -y
2、安装eslint(安装方式根据个人项目需要安装,这里使用全局安装)
$ npm install -g eslint
3、创建index.js文件,里面写一个函数。
function merge () {
var ret = {};
for (var i in arguments) {
var m = arguments[i];
for (var j in m) ret[j] = m[j];
}
return ret;
}
console.log(merge({a: 123}, {b: 456}));
执行node index.js,输出结果为{ a: 123, b: 456 }
$ node index.js
{ a: 123, b: 456 }
使用eslint检查
$ eslint index.js
Oops! Something went wrong! :(
ESLint: 4.19.1.
ESLint couldn't find a configuration file. To set up a configuration file for this project, please run:
eslint --init
ESLint looked for configuration files in E:\website\demo5\js and its ancestors. If it found none, it then looked in your home directory.
If you think you already have a configuration file or if you need more help, please stop by the ESLint chat room: https://gitter.im/eslint/eslint
执行结果是失败,因为没有找到相应的配置文件,个人认为这个eslint最重要的就是配置问题。
新建配置文件
$ 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? Yes
? Do you use JSX? No
? What style of indentation do you use? Tabs
? What quotes do you use for strings? Single
? What line endings do you use? Windows
? Do you require semicolons? No
? What format do you want your config file to be in? JavaScript
生成的内容在.eslintrc.js文件中,文件内容如下
module.exports = {
"env": {
"browser": true,
"commonjs": true,
"es6": true
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module"
},
"rules": {
"indent": [
"error",
"tab"
],
"linebreak-style": [
"error",
"windows"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"never"
]
}
};
不过这个生成的额文件里面已经有一些配置了,把里面的内容大部分删除。留下个extends,剩下的自己填就可以了
module.exports = {
"extends": "eslint:recommended"
};
eslint:recommended配置,它包含了一系列核心规则,能报告一些常见的问题。
重新执行eslint index.js,输出如下
10:1 error Unexpected console statement no-console
10:1 error 'console' is not defined no-undef
✖ 2 problems (2 errors, 0 warnings)
Unexpected console statement no-console --- 不能使用console
'console' is not defined no-undef --- console变量未定义,不能使用未定义的变量
一条一条解决,不能使用console的提示,那我们就禁用no-console就好了,在配置文件中添加rules
module.exports = {
extends: 'eslint:recommended',
rules: {
'no-console': 'off',
},
};