likes
comments
collection
share

ESLint + Prettier 编码规范化 + Husky 代码检测

作者站长头像
站长
· 阅读数 83

一、ESLint

ESLint最初是由 Nicholas C. Zakas 于2013年6月创建的开源项目。它的目标是提供一个插件化的可组装的 JavaScript 代码和 JSX 检查工具。

中文文档:

eslint.bootcss.com/

安装

npm i eslint babel-eslint

yarn add eslint babel-eslint

  1. eslint:ESLint 的核心代码。
  2. babel-eslint:eslint 与 babel 整合包。

使用命令后,会在当前文件夹中生成 .eslintrc 配置文件。

eslint --init

1. 配置文件

1.配置单独源文件 .js

/*
/* eslint-disable -- 取消eslint检测
/* global var1:false, var2:false	-- 指定全局变量
/* eslint-disable -- 禁用全部规则 放在文件顶部则整个文件范围都不检查
/* eslint-disable no-alert, no-console -- 禁用某些规则
/* eslint-disable-line -- 当前行上禁用规则 
/* eslint-disable-next-line -- 下一行上禁用规则
*/

2. 配置忽略检测文件 .eslintignore.json

node_modules
build/*.js
src/assets
public
dist

3. 配置文件 .eslintrc.*

eslint 配置文件既可以为 .json 也可以为 .js。

module.exports = {
  // 停止在父级目录中寻找
  root: true,
  // 指定环境
  env: {},
  // 指定全局变量
  // 1. 将每个全局变量名称设置为等于以 true 允许覆盖变量或 false 禁止覆盖
  // 2. 还支持在单独的 js 文件中通过注释配置全局变量 `/* global var1:false, var2:false */`
  globals: {},
  // 指定解析器 - 可以自定义解析器
  // parser: 'esprima';默认情况下,ESLint 使用 Espree 作为其解析器
  // 扩展配置文件,主要用来使用第三方的 eslint 的完整配置
  // 一般输出的是整个 eslint 配置,也可以是别的形式
  extends: [],
  // 配置解析器选项
  parserOptions: {},
  // 配置插件,使用第三方的 eslint 的 rules,命名格式 eslint-plugin-*
  // 插件一般输出的是规则
  plugins: [],
  // 禁用一组文件的配置文件中的规则
  overrides: [
    {
      files: ["*-test.js", "*.spec.js"],
      rules: {
        "no-unused-expressions": "off",
      },
    },
  ],
  // 配置规则
  // 1. 可以使用配置注释或配置文件来修改项目使用的规则
  // 2. 每个规则必须是以下的值
  // off 或者 0 关闭规则
  // warn 或者 1 将规则打开为警告(不影响退出代码)
  // error 或者 2 将规则打开为错误(触发时退出代码为1)
  rules: {},
};

2. 常用命令

  1. 查看所有命令行选项:eslint --h。
  2. 自动修复问题:eslint --fix。
  3. 禁用使用.eslintrc中的配置:eslint --no--eslintrc
  4. 对单个文件或文件目录进行格式化:eslint [options] [file|dir|glob]*。
  5. 使用指定目录中的其他规则:eslant --rulesdir [path::String]。
  6. 只报告错误,默认false:eslint --quiet。
  7. 只检查有改动的文件,默认false:eslint --cache。
  8. 明确格式化报告的输出文件:eslint --o, --output--file path::String。

3. 集成 ESLint

1. Webpack

  1. 安装

npm i eslint-webpack-plugin -D

  1. 配置:引入并使用插件
// 安装后导入
const ESLintPlugin = require('eslint-webpack-plugin');
// Webpack 配置
module.exports = {
  // 配置插件
	plugins: [ new ESLintPlugin(options)],
}

2. Rollup

  1. 安装

npm i eslint-webpack-plugin -D

  1. 配置:引入并使用插件
// 引入 rollup
import { rollup } from 'rollup'
// 引入插件
import { rollupESLintPlusin } from 'rollup'

export default{
  plugins: [
    // 使用插件
  	rollupESLintPlusin({
    	// options...
    })
  ]
}

3. Vite

  1. 安装

npm i -D eslint-config-prettier eslint-plugin-prettier

  1. 配置

新建 .eslintrc.js,更详细配置参考官网定制化开发。

module.exports = {
  env: {
    node: true,
  },
  extends: [
    "eslint:recommended", //
    "plugin:vue/vue3-essential",
    "plugin:prettier/recommended",
  ],
  globals: {
    defineProps: "readonly",
    defineEmits: "readonly",
    defineExpose: "readonly",
    withDefaults: "readonly",
  },
};

4. Vscod

  1. 安装扩展

前两个是格式化插件,Vetur 是 Vue 开发环境、代码提示插件。

ESLint + Prettier 编码规范化 + Husky 代码检测

ESLint + Prettier 编码规范化 + Husky 代码检测

ESLint + Prettier 编码规范化 + Husky 代码检测

  1. 配置 setting.json

复制粘贴下方代码到 setting.json 中,就可以实现每次保存自动格式化。

{
  "eslint.enable": true,
  "eslint.options": {
    "extensions": [
      ".js",
      ".vue",
      ".ts",
      ".tsx"
    ]
  },
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "eslint.validate": [
    "vue",
    "html",
    "javascript",
    "typescript",
    "javascriptreact",
    "typescriptreact"
  ],
  "vetur.format.defaultFormatter.html": "prettier"
}

Tips: 如果配置好后发现报错亦或者没有效果,那么很有可能是 Vetur 的 Format 规范与 Prettier 冲突了。

  1. 找到扩展,点击设置 --> 扩展设置

ESLint + Prettier 编码规范化 + Husky 代码检测

  1. 全部都选择 Prettier 即可

ESLint + Prettier 编码规范化 + Husky 代码检测

4. 参考配置

1. .eslintrc.js 规范配置

// .eslintrc.js

// @ts-check
const {
  defineConfig
} = require('eslint-define-config')
module.exports = defineConfig({
  root: true,
  env: {
    browser: true,
    node: true,
    es6: true
  },
  parser: 'vue-eslint-parser',
  parserOptions: {
    parser: '@typescript-eslint/parser',
    ecmaVersion: 2020,
    sourceType: 'module',
    jsxPragma: 'React',
    ecmaFeatures: {
      jsx: true
    }
  },
  extends: [
    'plugin:vue/vue3-recommended',
    'plugin:@typescript-eslint/recommended',
    // 'prettier',
    'plugin:prettier/recommended',
    'plugin:jest/recommended'
  ],
  rules: {
    'vue/script-setup-uses-vars': 'error',
    '@typescript-eslint/ban-ts-ignore': 'off',
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
    '@typescript-eslint/no-var-requires': 'off',
    '@typescript-eslint/no-empty-function': 'off',
    'vue/custom-event-name-casing': 'off',
    'no-use-before-define': 'off',
    '@typescript-eslint/no-use-before-define': 'off',
    '@typescript-eslint/ban-ts-comment': 'off',
    '@typescript-eslint/ban-types': 'off',
    '@typescript-eslint/no-non-null-assertion': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/no-unused-vars': [
      'error',
      {
        argsIgnorePattern: '^_',
        varsIgnorePattern: '^_'
      }
    ],
    'no-unused-vars': [
      'error',
      {
        argsIgnorePattern: '^_',
        varsIgnorePattern: '^_'
      }
    ],
    'space-before-function-paren': 'off',

    'vue/attributes-order': 'off',
    'vue/one-component-per-file': 'off',
    'vue/html-closing-bracket-newline': 'off',
    'vue/max-attributes-per-line': 'off',
    'vue/multiline-html-element-content-newline': 'off',
    'vue/singleline-html-element-content-newline': 'off',
    'vue/attribute-hyphenation': 'off',
    'vue/require-default-prop': 'off',
    'vue/html-self-closing': [
      'error',
      {
        html: {
          void: 'always',
          normal: 'never',
          component: 'always'
        },
        svg: 'always',
        math: 'always'
      }
    ]
  }
})

2. .eslintignore 忽略配置

*.sh
node_modules
*.md
*.woff
*.ttf
.vscode
.idea
dist
/public
/docs
.husky
.local
/bin

二、Prettier

  • 一个有态度的代码格式化工具。
  • 支持大量编程语言。
  • 已集成到大多数编辑器中。
  • 几乎不需要设置参数。

中文文档:

www.prettier.cn/

安装:

npm i prettier eslint-plugin-prettier eslint-config-prettier prettier-eslint-cli

yarn add prettier eslint-plugin-prettier eslint-config-prettier prettier-eslint-cli

  1. prettier:prettier 插件的核心代码。
  2. eslint-plugin-prettier:将 prettier 作为 ESLint 规范来使用。
  3. eslint-config-prettier:解决 ESLint 中的样式规范和 prettier 中样式规范的冲突,以 prettier 的样式规范为准,使 ESLint 中的样式规范自动失效。
  4. prettier-eslint-cli:允许你对多个文件用 prettier-eslint 进行格式化。

1. 配置 .prettierrc.js

module.exports = {
  // 最大长度 80 个字符
  printWidth: 80,
  // 使用单引号, 默认 false (在 jsx 中配置无效, 默认都是双引号)
  singleQuote: true,
  // 行末分号, 默认 true
  semi: true,
  // JSX 双引号
  jsxSingleQuote: false,
  // 尽可能使用尾随逗号(包括函数参数),默认 none,可选 none|es5|all
  // es5 包括 es5 中的数组、对象
  // all 包括函数对象等所有可选
  trailingComma: "all",
  // 在对象文字中打印括号之间的空格。 默认 true
  bracketSpacing: true,
  // 箭头函数参数括号 默认 avoid 可选 avoid | always
  // avoid 能省略括号的时候就省略 例如 x => x
  // always 总是有括号
  arrowParens: "avoid",
  // 在文件顶部插入一个特殊的 @format 标记,指定文件格式需要被格式化。
  insertPragma: false,
  // 行尾换行格式
  endOfLine: "auto",
  // html 空格敏感度
  htmlWhitespaceSensitivity: "ignore",
  // tab 缩进大小,默认为 2
  tabWidth: 2,
  // 使用 tab 缩进还是空格,默认 false
  useTabs: true,
  // vue 缩进脚本和样式
  vueIndentScriptAndStyle: false,
  // 标签放在最后一行的末尾,而不是单独放在下一行,默认 false
	jsxBracketSameLine: false,
};

2. 常用开源代码风格规范

1. Airbnb

Airbnb 是其中一个最流行的 JavaScript 代码规范,它差不多包含所有 JavaScript 的角度。校验比较严格。

Airbnb 规范的eslint实现:

  1. 安装

npm i eslint-config-airbnb

  1. 配置

.eslintrc.* 中加入:"extends": "airbnb"。

2. Standard

Standard 是一个标准的 JavaScript 代码规范,自带 linter & 代码自动修正。且使用时无须配置,是史上最便捷的统一代码风格的方式,轻松拥有。自带自动的代码格式化, 只需运行 standard --fix 从此和脏乱差的代码说再见。并且它还能提前发现代价风格以及程序问题。

  1. 安装

npm i eslint-config-standard

  1. 配置

.eslintrc.* 中加入:"extends":["standard"]

3. Prettier

Prettier 是一个代码格式化插件。它并不关心你的语法是否正确,只关心你的代码格式,比如是否使用单引号,语句结尾是否使用分号等等。但是有部分规则和Eslint的冲突。

  1. 安装

npm i eslint-config-prettier

  1. 配置

.eslintrc.* 中加入:"extends":["prettier"]

Tips: Vue-cli 中就自带了:ESLint + Airbnb,ESLint + Standard,ESLint + prettier 三种开发风格规范设置。

2. 参考配置

1. .prettierrc.js

module.exports = {
  printWidth: 100,
  tabWidth: 2,
  useTabs: false,
  semi: false,
  vueIndentScriptAndStyle: true,
  singleQuote: true,
  quoteProps: 'as-needed',
  bracketSpacing: true,
  trailingComma: 'all',
  jsxSingleQuote: false,
  arrowParens: 'always',
  insertPragma: false,
  requirePragma: false,
  proseWrap: 'never',
  htmlWhitespaceSensitivity: 'strict',
  endOfLine: 'auto',
};

三、Husky

自动阻止不合格 git commit,git push 操作。

GitHub 地址:

github.com/typicode/hu…

Husky 中文文档

www.breword.com/typicode-hu…

  1. 安装

npm i husky lint-staged -D

  1. 配置 .huskyrc.js
module.exports = {
  hooks: {
    // git commit 前的钩子
    "pre-commit": "lint-staged",
    "post-commit": "git update-index --again",
    "pre-push": "npm test"
  },
};
  1. 配置 lint-staged.config.js
module.exports = {
  "src/**/*.{js,vue}": ["eslint --fix", "git add"],
  "src/**/*.{vue,html,css,scss,sass}": ["stylelint --fix", "git add"],
  "src/**/*.{js,vue,html,css,scss,sass}": [    "prettier-eslint --write",    "git add",  ],
};