代码品质(前端 vscode)

在一个我的项目中,因为每个人编写代码的格调不一样,对代码的格局下面有一个束缚,将会大大提高代码的品质。

eslint

lint在计算机中是一个动态程序剖析工具,用来标记代码中可疑的,可能会呈现bug的语句。

装置

npm i -D eslint

生成配置文件

npx eslint --init

运行下面,抉择相应的配置项,这个命令做了两件事

1.生成.eslintrc.js 配置文件,依据你的选项不同会有稍微出入

module.exports = {  root: true, // 限定配置文件应用范畴  env: {    // 指定代码运行环境    browser: true, // browser global variables    es2021: true, //  },  parserOptions: {    ecmaVersion: "latest", //ECMAScript 版本    sourceType: "module", //ECMAScript 模块  },  // 继承第三方格调  extends: [    "airbnb-base", // 全名eslint-config-airbnb-base,可省略eslint-config  ],  rules: {},};

2.下载对应的第三方 eslint 配置,我选的 airbnb 格调的,所以下了 eslint-config-airbnb-base,而 eslint-config-airbnb-base 依赖于 eslint-plugin-import,所以总共下载了两个依赖

代码查看

npx eslint ./须要查看语法的文件门路

配置编辑器

这时候能对代码进行查看了,但只有运行命令的时候才会显示谬误,所以为了不便咱们开发,vscode 装置插件 ESlint,这个时候就能间接看到文件的报错了,就不必去运行命名了

减少.eslintignore 疏忽文件

减少疏忽文件,疏忽一些文件不进行 eslint 查看

.eslintignore

# 以”#”号结尾示意正文;# 以斜杠“/”结尾示意目录;# 以星号“*”通配多个字符;# 以问号“?”通配单个字符# 以方括号“[]”蕴含单个字符的匹配列表;# 以叹号“!”示意不疏忽(跟踪)匹配到的文件或目录;# *.txt  ,*.xls  示意过滤某种类型的文件# target/ :示意过滤这个文件夹下的所有文件# /test/a.txt ,/test/b.xls  示意指定过滤某个文件下具体文件# !*.java , !/dir/test/     !结尾示意不过滤# *.[ab]    反对通配符:过滤所有以.a或者.b为扩展名的文件# /test  仅仅疏忽我的项目根目录下的 test 文件,不包含 child/test等非根目录的test目录/dist/build

打包代码进行 eslint 查看

须要插件 eslint-webpack-plugin

装置

npm i -D eslint eslint-webpack-plugin eslint-config-airbnb-base eslint-plugin-import

webpack.config.js 配置

const ESLintPlugin = require("eslint-webpack-plugin");module.exports = {  plugins: [new ESLintPlugin()],};

stylelint

装置

npm i -D stylelint stylelint-config-standard stylelint-prettier stylelint-config-prettiernpm i -D stylelint-less stylelint-config-recommended-less postcss-less

减少.stylelintrc.js

module.exports = {  plugins: ["stylelint-prettier"],  extends: [    "stylelint-config-standard",    "stylelint-config-recommended-less",    "stylelint-config-prettier",  ],  customSyntax: "postcss-less",  rules: {    "prettier/prettier": true,  },};

Prettier

ESLint 次要负责解决两种规定:格式化和代码品质问题。格式化不是它的强项,须要用 Prettier 格式化巨匠来解决代码格调有问题的代码。

Prettier 格式化后的代码,实践上是最难看的。正因为 Prettier 只关注格式化,所以它也能够格式化其它的文件。

装置

npm i -D prettier

减少配置文件
.prettier.js

module.exports = {};

编辑器装置 Prettier -code formatter 插件,能够一键格式化文档

编辑器 settings.josn 减少配置,保留的时候格式化

"editor.formatOnSave": true, //开启主动保留"editor.defaultFormatter": "esbenp.prettier-vscode", //默认格式化工具抉择prettier

eslint 和 prettier 配合应用

prettier 是善于代码格局的校验,eslint 善于代码品质的校验。虽说 eslint 也能格局校验,然而并没有 prettier 那么强势。

当你用 Prettier 格式化代码后再用 ESLint 去检测,会呈现一些因为格式化导致的 warning。

eslint-plugin-prettier 插件会调用 prettier 对你的代码格调进行查看,其原理是先应用 prettier 对你的代码进行格式化,而后与格式化之前的代码进行比照,如果过呈现了不统一,这个中央就会被 prettier 进行标记,最初 eslint 主动 fix 依照 prettier 的标准修复 error 代码

装置

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

.eslintrc.js

extends: ["airbnb-base", "plugin:prettier/recommended"],

有时候配置好后重启 vscode 能力失效

配置 vscode

减少配置文件

在我的项目根目录下

编辑器配置

{  "editor.formatOnSave": true, //开启保留的时候格式化  "eslint.enable": true, //是否开启vscode的eslint  "eslint.alwaysShowStatus": true, //右下角显示eslint图标  "editor.codeActionsOnSave": {    "source.fixAll.eslint": true // 在保留的时候用eslint修复和prettier不抵触局部谬误  },  "editor.defaultFormatter": "esbenp.prettier-vscode", //默认格式化工具抉择prettier}

.editorconfig

增加 .editorconfig 文件,编辑器配置文件。.editorconfig 配置文件用于抹平不同编辑器或零碎之间的编码差别,放在我的项目根目录。最常见的配置之一是 end_of_line = lf,如果用 Windows 和 Mac 混合开发,不对立行尾符会造成 eslint 爆红。

因为不同开发者的编辑器设置不同,故在我的项目中该当蕴含 .editorconfig,用来对立配置编辑器的换行、缩进存储格局。

配置

# http://editorconfig.orgroot = true[*]indent_style = space                    # 输出的 tab 都用空格代替indent_size = 2                         # 一个 tab 用 2 个空格代替end_of_line = lf                      # 换行符应用 unix 的换行符 \ncharset = utf-8                         # 字符编码 utf-8trim_trailing_whitespace = true         # 去掉每行开端的空格insert_final_newline = true             # 每个文件开端都加一个空行[*.md]trim_trailing_whitespace = false        # .md 文件不去掉每行开端的空格

husky

GitHook 工具, 联合 eslint,对提交到仓库的代码进行 eslint 检查和修复

运行命令

# 装置哈士奇npm install husky -D# 增加 prepare 命令npm set-script prepare "husky install"# prepare 创立 bash 脚本,装置 git hooksnpm run prepare# 增加 pre-commit 的 git hook 脚本npx husky add .husky/pre-commit "npx eslint src --fix"

运行之后会发现在 ./.husky/pre-commit 里看到 git commit 前会运行的脚本:

#!/bin/sh. "$(dirname "$0")/_/husky.sh"# git commit 前先 eslint fix 一波npx eslint src --fix

然而这样的命令会让每次 commit 前都把整个 src 都扫描并 fix 一次,速度太慢了,而且很容易把他人的屎山也 fix 掉,而后提交下来。

lint-staged

咱们更心愿只针对提交的文件进行 Lint 操作,能够应用 lint-staged

Lint-staged 仅仅是文件过滤器,查看本次提交所批改(指 git 暂存区里的货色)的问题

装置

npm i -D lint-staged

而后增加 .lintstagedrc.js 配置文件,外面对提交不同的文件进行 eslint --fix 操作。

.lintstagedrc.js

module.exports = {  "**/*.{ts,tsx,js,jsx}": [    "eslint --cache --fix --cache-location ./node_modules/.cache/.eslintcache",  ],  "**/*.vue": [    "eslint --cache --fix --cache-location ./node_modules/.cache/.eslintcache",  ],  "**/*.{css,less}": [    "stylelint --cache --fix --cache-location ./node_modules/.cache/.eslintcache",  ],};

lint-staged 配置的含意是对提交上来不同类型的文件执行对应的 lint fix 命令。

最初在刚刚创立的 ./.husky/pre-commit 里改成执行 lint-staged 命令:

#!/bin/sh. "$(dirname "$0")/_/husky.sh"npx lint-staged

当前每次 commit 前都会跑一次 lint-staged,而 lint-staged 又会对提交的文件进行 ESLint Fix。

commitizen 和 commitlint

  • commitizen:基于 Node.js 的 git commit 命令行工具,辅助生成标准化规范化的 commit message。
  • cz-git:一款工程性更强,轻量级,高度自定义,规范输入格局的 commitizen 适配器
  • commitlint:commitlint 校验提交信息
  • @commitlint/config-conventional:commitlint 规定集

对 git commit 依照对立的格调来提交,这样能够疾速定位每次提交的内容,不便之后对版本进行管制。

装置

npm install commitizen cz-git @commitlint/config-conventional @commitlint/cli -D

在 package.json 中配置

"config": {    "commitizen": {      "path": "node_modules/cz-git"    }  }

减少 .commitlintrc.js 配置文件

// .commitlintrc.js/** @type {import('cz-git').UserConfig} */module.exports = {  rules: {    // @see: https://commitlint.js.org/#/reference-rules  },  extends: ["@commitlint/config-conventional"],  prompt: {    alias: { fd: "docs: fix typos" },    messages: {      type: "Select the type of change that you're committing:",      scope: "Denote the SCOPE of this change (optional):",      customScope: "Denote the SCOPE of this change:",      subject: "Write a SHORT, IMPERATIVE tense description of the change:\n",      body: 'Provide a LONGER description of the change (optional). Use "|" to break new line:\n',      breaking:        'List any BREAKING CHANGES (optional). Use "|" to break new line:\n',      footerPrefixesSelect:        "Select the ISSUES type of changeList by this change (optional):",      customFooterPrefix: "Input ISSUES prefix:",      footer: "List any ISSUES by this change. E.g.: #31, #34:\n",      confirmCommit: "Are you sure you want to proceed with the commit above?",    },    types: [      { value: "feat", name: "feat:     A new feature", emoji: ":sparkles:" },      { value: "fix", name: "fix:      A bug fix", emoji: ":bug:" },      {        value: "docs",        name: "docs:     Documentation only changes",        emoji: ":memo:",      },      {        value: "style",        name: "style:    Changes that do not affect the meaning of the code",        emoji: ":lipstick:",      },      {        value: "refactor",        name: "refactor: A code change that neither fixes a bug nor adds a feature",        emoji: ":recycle:",      },      {        value: "perf",        name: "perf:     A code change that improves performance",        emoji: ":zap:",      },      {        value: "test",        name: "test:     Adding missing tests or correcting existing tests",        emoji: ":white_check_mark:",      },      {        value: "build",        name: "build:    Changes that affect the build system or external dependencies",        emoji: ":package:",      },      {        value: "ci",        name: "ci:       Changes to our CI configuration files and scripts",        emoji: ":ferris_wheel:",      },      {        value: "chore",        name: "chore:    Other changes that don't modify src or test files",        emoji: ":hammer:",      },      {        value: "revert",        name: "revert:   Reverts a previous commit",        emoji: ":rewind:",      },    ],    useEmoji: false,  },};

应用 husky 生成 commit-msg 文件,验证提交信息:(对提交信息进行拦挡)

npx husky add .husky/commit-msg "npx --no-install commitlint --edit $1"

这个时候就可拦挡了,能够自定义代码提交格调