Bambooom

ESLint 简易教程

3 min read

简介

安装

# 推荐项目本地安装, 而不是全局安装
$ npm install eslint --save-dev

# 列出所有可用命令
$ ls -la node_modules/.bin
# 结果
...
eslint -> ../eslint/bin/eslint.js
...

使用

初始化配置文件

$ ./node_modules/.bin/eslint --init
# /node_modules/* and /bower_components/* ignored by default

# Ignore built files except build/index.js
build/*
!build/index.js

针对某个文件 file.js 进行检查

$ ./node_modules/.bin/eslint file.js

-> 直接在命令行打印出相关 error/warning

$ ./node_modules/.bin/eslint file.js --fix

-> 使用 --fix 选项可以直接自动修正, 主要修正 whitespaces 问题, 其他可修正的问题可参考官方文档中列出的 rules 中带🔧项

$ ./node_modules/.bin/eslint file.js -o lintResult.html -f html

-> 上面命令将检查报告输出为 lintResult.html 静态页面, 并将在浏览器中打开此页面, 易于阅读, 其他报告模式可参考官方文档 - formatter

对某些需要特殊处理的部分, 可在代码中使用注释更改 eslint 规则, 例如:

/* eslint-disable no-alert, no-console */

alert('foo');
console.log('bar');

/* eslint-enable no-alert, no-console */

针对 React 项目