eslint是一个插件化的javascript和jsx代码检测工具,eslint使用Node.js编写。
全局安装的eslint只能使用全局安装的插件,本地安装的eslint不仅可以使用本地安装的插件还可以使用全局安装的插件。
一、如何启用eslint进行代码检查?
1、安装eslint相关
cnpm i -D eslint eslint-loader eslint-plugin-html
2、eslint的使用方法
A、在js代码中写注释
比如在js文件中用注释指定环境
/* eslint-env node, mocha */
B、新建配置文件
eslint支持多种形式的配置文件,如果同一个目录下有多个配置文件,eslint只会使用一个。优先级顺序如下:
.eslintrc.js
module.exports = { root: true, parser: 'babel-eslint', parserOptions: { sourceType: 'module' }, env: { browser: true, }, // https://github.com/standard/standard/blob/master/docs/RULES-en.md extends: 'standard', // required to lint *.vue files plugins: [ 'html' ], // add your custom rules here 'rules': { // allow paren-less arrow functions 'arrow-parens': 0, // allow async-await 'generator-star-spacing': 0, // allow debugger during development 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0 } }
.eslintrc.json
{ "env":{ "es6": true }, "parserOptions": { "ecmaVersion": 6, "sourceType": "module", "ecmaFeatures": { "jsx": true } }, "rules": { "semi": 2 } }
.eslintrc
{ "env": { "mocha": true }, "globals": { "expect": true, "sinon": true } }
package.json
{ "name": "testvue", "version": "1.0.0", "description": "", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "server": "webpack-dev-server --open", "build": "webpack-dev-server" }, "author": "camille", "license": "ISC", "devDependencies": { "css-loader": "^0.28.7", "eslint": "^4.9.0", "eslint-loader": "^1.9.0", "eslint-plugin-html": "^3.2.2", "style-loader": "^0.19.0", "vue": "^2.5.2", "vue-loader": "^13.3.0", "vue-template-compiler": "^2.5.2" }, "eslintConfig": { "env": { "browser": true }, "plugins": [ "html" ] } }
二、eslint怎么查找配置文件?
你可能会好奇eslint怎么查找配置文件,一般情况下,是通过自动查找,也可以手动指定。
1、自动查找
eslint会自动在要检测的文件目录里寻找配置文件,紧接着是父级目录,一直到文件系统的根目录。
2、命令行指定
可以在子目录新建配置文件,通过命令行,对某个js文件进行代码规范检查。
# 为myfiletotest.js文件指定一个额外的(除了.eslint.*或者package.json文件)配置文件 eslint -c myconfig.json myfiletotest.js # 检查.vue扩展名的文件 eslint --ext .vue MyComponent.vue # 检查lib文件夹下的js和jsx文件 eslint --ext .jsx,.js lib/
三、.eslintignore文件
该文件是一个纯文本文件。举个例子:
# /node_modules/* and /bower_components/* ignored by default # Ignore built files except build/index.js build/* !build/index.js
把.eslintignore文件放到当前工作目录里,将忽略node_modules,bower_components以及build/目录下除了build/index.js的所有文件。