使用React框架之工欲善其事,必先利其器

2,328 阅读3分钟

第一步: 配置eslint stylelint pretter

@umijs/fabric一个包含 prettier,eslint,stylelint 的配置文件合集。使用大厂的配置规范肯定比自己配置要好

相关插件的安装

yarn add @umijs/fabric -D

默认@umijs/fabric已经给我们安装了需要的依赖,但是默认是没有pretter的,所以需要我们安装一下,剩下有问题可以根据提示安装。

yarn add pretter check-prettier -D

新建 .eslintrc.js .eslintignore

.eslintrc.js用来使用@umijs/fabric中的规则。我们也可以根据自己的需要增加自己的规则。

module.exports = {
  extends: [require.resolve('@umijs/fabric/dist/eslint')],
  globals: {
    __REDUX_DEVTOOLS_EXTENSION__: true,
  },
  rules: {
    'indent': [22, {'SwitchCase'1}], // 缩进
    'no-irregular-whitespace'2// 不允许不规则空白
    'no-mixed-spaces-and-tabs'2// 不允许混合空格和制表符缩进
    'no-multi-spaces'2// 不允许多个空格
    'no-multiple-empty-lines': [2, {'max'1}], // 不允许多个空行
    'no-spaced-func'2// 函数调用间隔
    'space-before-function-paren': [2'never'], // 在“function”定义的左括号前强制使用一致间距
    'use-isnan'2
  }
};

.eslintignore是用来忽略eslint检测的文件

/lambda/
/scripts/*
.history
serviceWorker.ts
/config/*
/public/*
*.js

新建.prettierrc.js .prettierignore

const fabric = require('@umijs/fabric');
module.exports = {
  ...fabric.prettier,
};
**/*.svg
package.json
.umi
.umi-production
/dist
.dockerignore
.DS_Store
.eslintignore
*.png
*.toml
docker
.editorconfig
Dockerfile*
.gitignore
.prettierignore
LICENSE
.eslintcache
*.lock
yarn-error.log
.history

新建.stylelintrc.js

const fabric = require('@umijs/fabric');
module.exports = {
  ...fabric.stylelint,
};

新建命令

package.json > scripts 中添加命令

  "scripts": {
    + "lint""npm run lint:js && npm run lint:style && npm run lint:prettier",
    + "lint-staged""lint-staged",
    + "lint-staged:js""eslint --ext .js,.jsx,.ts,.tsx --ignore-path .eslintignore .",
    + "lint:fix""eslint --fix --cache --ext .js,.jsx,.ts,.tsx --format=pretty ./src && npm run lint:style",
    + "lint:js""eslint --cache --ext .js,.jsx,.ts,.tsx --format=pretty ./src --ignore-path .eslintignore .",
    + "lint:prettier""check-prettier lint --ignore-path .eslintignore .",
    + "lint:style""stylelint --fix \"src/**/*.less\" --syntax less",
    + "prettier""prettier -c --write \"**/*\""
  },

当执行这些命令的时候会自动根据规则检查修复代码。yarn lint yarn lint:fix yarn lint:style

提交前校检规则

使用husky lint-staged在commit的时候校检你提交的代码是否符合规范。如果存在不规范的地方会进行自动修复,有些地方可能修复不了,会提示提交失败。

yarn add husky lint-staged -D
// package.json
"lint-staged": {
  "**/*.less": "stylelint --syntax less",
  "**/*.{js,jsx,ts,tsx}": "npm run lint-staged:js",
  "**/*.{js,jsx,tsx,ts,less,md,json}": [
    "prettier --write"
  ]
},
"husky": {
  "hooks": {
    "pre-commit": "npm run lint-staged"
  }
},

假如提交的代码不符合规范,会有如下的提示。

commit失败
commit失败