项目没有一个统一的规范和代码风格看起来既难受又不利于维护,随着项目接手的人越多项目就会越来越乱,久而久之就成了所谓的屎山。
不以规矩,不成方圆
lint 规则
安装 eslint 和相关的包npm i eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin -D
,根目录下创建.eslintrc.js,和.eslintignore 文件。前者为 eslint 的检测规则,后者为不参与检测的文件。
在.eslintrc.js 中添加如下内容,具体的配置可以看 eslint 官网配置项。以下为我的配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| module.exports = { root: true, parser: "@typescript-eslint/parser", env: { browser: true, es6: true, node: true, }, parserOptions: { ecmaFeatures: { jsx: true, }, ecmaVersion: 2018, sourceType: "module", }, extends: [ "eslint:recommended", "eslint:recommended", "plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended", "plugin:react/recommended", ], plugins: ["@typescript-eslint", "prettier", "react", "react-hooks"], rules: { "react-hooks/rules-of-hooks": "error", "react-hooks/exhaustive-deps": "warn", "no-console": "warn", "no-debugger": "off", "no-unused-vars": "warn", }, };
|
然后再 package.json 中添加 script
1 2 3 4 5 6
| { "scripts": { "lint": "eslint . --ext .ts && eslint . --ext .tsx", "lint:fix": "eslint --fix" } }
|
prettier 规范
在根目录创建.prettierrc.js 文件(同理也可以创建.prettierignore).prettierrc.js 中添加如下内容,具体的配置可以看 prettierrc 官网配置项。以下为我比较习惯的 react 项目的配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| module.exports = { printWidth: 100, tabWidth: 2, semi: true, singleQuote: false, endOfLine: "auto", bracketSpacing: true, arrowParens: "avoid", trailingComma: "es5", quoteProps: "consistent", };
|
这时你就可以使用npx prettier --write [文件目录]
格式化想要的文件了
可以在 vscode 的 setting.json 中添加如下代码在保存和粘贴的时候格式化代码
1 2
| "editor.formatOnPaste": true, "editor.formatOnSave": false
|
commit 规则
新建.commitlintrc.js 文件,添加如下规范。这个也是目前主流的 commit 规则,我看好多 git 上的项目使用的都是这一套规范,安装依赖npm i @commitlint/cli @commitlint/config-conventional -D
。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| module.exports = { extends: ["@commitlint/config-conventional"], rules: { "type-enum": [ 2, "always", [ "feat", "fix", "bugfix", "docs", "style", "refactor", "test", "revert", "config", "chore", "message", ], ], "type-empty": [2, "never"], "subject-empty": [2, "never"], "subject-full-stop": [0, "never"], "subject-case": [0, "never"], }, };
|
规则配置就绪后,我们可以添加 git 的钩子,在 pre-commit 的时候执行规则。安装npm i husky@4.3.8 lint-staged -D
。踩坑:尽量安装该版本的 husky,我在使用 7.0.1 版本的时候 commit 无法触发改检验。 使用新版的husky需执行husky install
生成.husky文件,然后创建pre-commit
和commit-msg
文件 写入对应内容,还需要给这两个文件加上+x权限(操作权限)chmod +x pre-commit commit-msg
然后package.json
的最外层添加如下代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| { ... "lint-staged": { "*.{jsx,ts,tsx,js}": [ "node -v", "npm run lint:fix", "prettier --write " ] }, "husky": { "hooks": { "commit-msg": "commitlint -E HUSKY_GIT_PARAMS", "pre-commit": "lint-staged" } } ... }
|
这样你在 commit 之前就会先检验 commit 内容是否符合规范,然后就是当前 node 版本,然后检测 lint 规则,最后就是格式化代码。此处的prettier只会格式化本次提交有改动的文件