eslint 简单使用方法
eslint 是在 ECMAScript/JavaScript 代码中识别和报告模式匹配的工具,它的目标是保证代码的一致性和避免错误。两种安装方式
全局
适用于所有项目文件
先全局安装ESLint插件
$ npm install -g eslint
初始化配置文件
eslint --init
使用
eslint file.js
本地
项目里使用
npm install eslint --save-dev
react plugins
npm install --save-dev eslint-plugin-react
目前项目中用的airbnb代码规范
npm install --save-dev eslint-config-airbnb
项目中初始化配置文件
./node_modules/.bin/eslint --init
然后选择使用airbnb的方式
? How would you like to configure ESLint? Use a popular style guide
? Which style guide do you want to follow? AirBnB
? What format do you want your config file to be in? JavaScript
运行
./node_modules/.bin/eslint file.js
autofix
只支持空格分号等,链接
./node_modules/.bin/eslint file.js --fix
配置文件
init 初始化配置文件后,项目中会得到一个.eslintrc.js的文件。当然还会有.json YAML等格式的。
module.exports = { "extends": "airbnb",//拓展规则 "plugins": [//插件 "react", "jsx-a11y", "import" ], "env": {//指定环境 "browser": true, "node": true }, "rules": {//规则 "semi": "error" } }
package.json 中使用
"name": "mypackage",
"version": "0.0.1",
"eslintConfig": {
"plugins": ["react"],
"env": {
"browser": true
}
}
Rules
- "off" 或 0 - 关闭规则
- "warn" 或 1 - 开启规则,使用警告级别的错误:warn (不会导致程序退出)
- "error" 或 2 - 开启规则,使用错误级别的错误:error (当被触发的时候,程序会退出)
如果采用了拓展规则,比如说airbnb,会有默认的,再node_module中都有rules,那配置文件就不用再多写了。但是我们可以写一些,覆盖拓展里的,以达到关闭某些规则的作用。
例如
这些规则都可以google一下
"rules": {
"react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }],
"react/forbid-prop-types": 0,
"react/no-array-index-key": 0,
"react/jsx-wrap-multilines": 0,
"react/prop-types": 1,
"jsx-a11y/no-static-element-interactions": 0,
"no-underscore-dangle": 0,
"no-script-url": 0,
"class-methods-use-this": 0,
"no-constant-condition": 0,
"max-len": 0,
"no-nested-ternary": 0,
"semi": 1,
"space-before-function-paren": 1
}
.eslintignore
可以在项目根目录创建,告诉 ESLint 忽略某些文件或者目录。相当于 .gitignore 都是纯文本文件。例如
# 注释,忽略文件
node_modules
**/.js
build
配合 webpack 的使用
安装一个 eslint-loader 的 loader
module:{
preLoaders: [
{test: /.js$/, loader: "eslint-loader", exclude: /node_modules/}
],
loaders:[
{
test:/.jsx?$/,
exclude:/node_modules/,
loader:'babel'
},
{
test:/.css$/,
loaders:['style','css'],
include:'/dist'
}]
}
结合 pre-commit 使用
有时候可能我们的项目后入 eslint,之前的文件太多,改不过来,但是却要慢慢加入。可以加一个 git 的 hooks。
项目本地安装
npm install --save-dev pre-commit
package.json 配置,例如
{
"script": {
"lint": "git diff-tree --no-commit-id --name-only -r $REVISION | xargs pre-commit run --files."
},
"pre-commit": [
"lint"
],
}
git 钩子(可自定义)
钩子都被存储在 Git 目录下的 hooks 目录中
cd .git/hooks && ls
这些钩子的功能主要分为提交工作流钩子、电子邮件工作流钩子和其它钩子。比如提交代码之前检查,提交给同组开发人员发邮件等等。
当然 eslint 也可以结合 gulp,以及在编译器中使用。这些从网上都可以查到。比如我现在 atom 用到的就直接下载 bao 包了
apm install linter-eslint
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

上一篇: Linux 常用命令学习笔记
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论