Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ESLint 检查,在 vue 项目中使用,以及 git 勾子 #20

Open
NoName4Me opened this issue Aug 6, 2018 · 0 comments
Open

ESLint 检查,在 vue 项目中使用,以及 git 勾子 #20

NoName4Me opened this issue Aug 6, 2018 · 0 comments
Labels
vue vue系列文章 尺规

Comments

@NoName4Me
Copy link
Owner

NoName4Me commented Aug 6, 2018

约定规则

建议规则

module.exports = {
  "env": {
    "browser": true,
    "es6": true
  },
  "plugins": ['vue'],
  "extends": ["eslint:recommended", "plugin:vue/recommended"],
  "parserOptions": {
    "parser": "babel-eslint",
    "ecmaVersion": 6,
    "sourceType": "module"
  },
  "rules": {
    "indent": [
      "error",
      2
    ],
    "quotes": [
      "error",
      "single"
    ],
    "semi": [
      "error",
      "never"
    ],
    "eqeqeq": [
      "error",
      "always"
    ]
  }
};

使用 eslint

基础

有两种配置方式:

  1. 在代码里直接用注释方式配置;
  2. 使用统一的配置文件(JavaScriptJSONYAML 格式,根目录下对整个目录及子目录生效,子目录下也可以有配置,就近生效,文件名如 .eslintrc.* 或者在 package.jsoneslintConfig 属性,当然也可以在命令行中指定特定文件)。

关于优先级的一个特别说明: .eslintrc.*package.json 都存在时,后者忽略,如果某个目录不想继承父目录的配置,可以增加 "root": true

  • 一个示例
module.exports = {
  env: {
    es6: true // 支持 ES6 新全局变量,如 Set
  },
  parserOptions: {
      ecmaVersion: 6, // 用 ECMAScript 5 语法解析,等同于 2015
      sourceType: "module", // 代码在 ECMAScript 里,默认值为 script
      ecmaFeatures: {
          jsx: true
      }
  },
  rules: {
      semi: 2
  }
}

ESLint 使用 Espree 作为解析器,也可以使用其它解析器,不推荐,but,大家好像都喜欢用 babel-eslint 做解析器呢。

环境变量

  • browser - browser global variables.
  • node - Node.js global variables and Node.js scoping.
  • commonjs - CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack).
  • shared-node-browser - Globals common to both Node.js and Browser.
  • es6 - enable all ECMAScript 6 features except for modules (this automatically sets the ecmaVersion parser option to 6).
  • worker - web workers global variables.
  • amd - defines require() and define() as global variables as per the amd spec.
  • mocha - adds all of the Mocha testing global variables.
  • jasmine - adds all of the Jasmine testing global variables for version 1.3 and 2.0.
  • jest - Jest global variables.
  • jquery - jQuery global variables.

用法:

{
  "env": {
      "browser": true,
      "node": true
  }
}

如果你想使用一个插件(如example)的环境变量(custom),可以这样写:

{
  "plugin": ["example"],
  "env": {
    "example/custom": true
  }
}

全局变量

{
  "globals": {
    "var1": true,
    "var2": false
  }
}

配置规则

等级:

  • "off"/0 关闭
  • "warn"/1 打开规则,只告警 (doesn’t affect exit code)
  • "error"/2 打开规则,报错 (exit code is 1 when triggered)。

忽略规则

  • 代码内忽略
// 忽略行
alert('foo'); // eslint-disable-line

// eslint-disable-next-line
alert('foo');

/* eslint-disable-next-line */
alert('foo');

// 忽略部分
/* eslint-disable */
alter('foo');
console.log('hi');
/* eslint-enable */

// 整个文件忽略(指定规则)
/* eslint-disable no-alert */
alert('foo');
  • 重写规则
{
  "rules": {...},
  "overrides": [ // 这里
    {
      "files": ["bin/*.js","lib/*.js"],
      "excludedFiles": "*.test.js",
      "rules": {
        "quotes": [2, "single"]
      }
    }
  ]
}
  • .eslintignore 忽略
# 项目根目录下的 /node_modules/* 和 /bower_components/* 默认会被忽略

# 忽略除了 build/index.js 外,其它所有在 build 目录下的文件
build/*
!build/index.js

extend 扩展

{
  "extends": [
    "eslint:recommended",
    // 扩展文件
    "./node_modules/coding-standard/eslintDefaults.js",
  ],
  "rules": {
    "quotes": [1, "single"] // 比如扩展的是 [2, "single"],最终就是[1, "single"]
  }
}

为项目引入配置 eslint

注意:不要全局和局部混用,比如使用全局eslint,却调用局部解析器。

  • 已有项目
# 安装, eslint | babel-eslint解析器 | vue eslint 插件
npm install eslint babel-eslint eslint-plugin-vue --save-dev

# 初始化,可以不执行这个,自己新建 .eslintrc.* 文件即可
./node_modules/.bin/eslint --init

# lint 某个文件
./node_modules/.bin/eslint src/main.js

配置 package.json 中的脚本

注意eslint '**/*.js' 加单引号解决和 shell 的 glob 冲突问题

{
  // 只提示不修复
  "lint": "./node_modules/.bin/eslint 'src/**/*.{js,vue}';exit 0",
  // 修复,并提示无法修复的
  "lf": "./node_modules/.bin/eslint --fix 'src/**/*.{js,vue}';exit 0"
}

git hook

.git/hooks 目录下,新建 pre-commit 文件。

#!/bin/bash

STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM -- "*.js" "*.vue")

if [[ "$STAGED_FILES" = "" ]]; then
  exit 0
fi

PASS=true
echo -e "\n>>>>开始ESLint检查....\n"

# Check for eslint
which ./node_modules/.bin/eslint &> /dev/null
if [[ "$?" == 1 ]]; then
  echo -e "\t\033[41m请先安装ESlint\033[0m"
  exit 1
fi

for FILE in $STAGED_FILES
do
  ./node_modules/.bin/eslint "$FILE"
  if [[ "$?" == 0 ]]; then
    echo -e "\t\033[32mESLint检查通过: $FILE\033[0m"
  else
    echo -e "\t\033[41mESLint检查失败: $FILE\033[0m"
    PASS=false
  fi
done
echo -e "\n>>>>检查完毕~\n"
if ! $PASS; then
  echo -e "\033[41mCOMMIT FAILED:\033[0m 此次提交包含没有通过ESLint检查的文件,请修改后再提交!\n"
  exit 1
else
  echo -e "\033[42mCOMMIT SUCCEEDED\033[0m\n"
fi
cd -
exit $?

它会在对比 git add 的修改文件,然后在 commit 时执行 ESLint 检查,如果检查失败则不会提交。

由于.git 目录不会提交到 git 仓库,所以需要额外配置此文件的拷贝操作,在 package.json 中增加脚本:

"hook": "cp git-hooks/pre-commit .git/hooks/;chmod 775 .git/hooks/pre-commit"

说明:

# 有的时候可能会没有权限,完备起见,每次都执行一下赋权
chmod 775 .git/hooks/pre-commit

跳过勾子:

git commit --no-verify

参考


  1. Vue 官方 ESLint 插件: https://github.com/vuejs/eslint-plugin-vue
  2. ESLint 官方Doc: https://eslint.org/docs/rules/
@NoName4Me NoName4Me added vue vue系列文章 尺规 labels Aug 6, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
vue vue系列文章 尺规
Projects
None yet
Development

No branches or pull requests

1 participant