xccjk / x-blog

学习笔记
17 stars 2 forks source link

怎么打造适合前端团队的代码规范? #27

Closed xccjk closed 2 years ago

xccjk commented 3 years ago

前言

在现在的前端开发中,项目常常由多个人共同维护,但是由于每个人的代码风格、提交规范方面、编辑器设置等各方面的原因,导致提交上去的代码风格没有保持统一,常见的有下列几个问题:

为了保证代码风格统一,便于后期的维护,我们需要使用检查工具来检查自己的代码,常见的几个检查场景:

代码已上传到githubgithub

项目背景

在之前的业务场景下,平时配置一些代码检查规范,为了拥有对应的检查功能,需要分别安装很多三方包,新建配置文件来达到效果,并且想在其他项目中也配置相同的配置时,需要重复安装众多的包,而且还难以保证包版本一致,导致不同项目间可能存在差异

打造统一规范代码插件

目的

使用方式

安装相关依赖

  npm install xcc-standard-eslint eslint-plugin-react eslint
  npm install xcc-standard-prettier
  npm install xcc-standard-stylelint
  npm install xcc-commitlint husky lint-staged
  npm install conventional-changelog-cli

eslint相关

官网解释:eslint为一个插件化的JavaScript工具,目标是保证代码的一致性和避免错误

  npm install xcc-standard-eslint eslint-plugin-react eslint

.eslintrc.js


  // ts中常用配置方式
  const { getEslint } = require('xcc-standard-eslint')

  module.exports = {
    ...getEslint({
      ignorePatterns: ['.dll', 'build', '.temp'],
      useTs: true,
      // 需要覆盖默认的配置规则,在有些老项目中可能为了维持稳定,不改变之前的逻辑,就需要兼容之前的语法规则
      rules: {
        'comma-dangle': 'off',
        'function-paren-newline': 'off',
        'global-require': 'off',
        'import/no-dynamic-require': 'off',
        'no-inner-declarations': 'off',
        'class-methods-use-this': 'off',
        'import/extensions': 'off',
        'import/prefer-default-export': 'off',
        '@typescript-eslint/explicit-function-return-type': 'off',
        '@typescript-eslint/no-var-requires': 'off',
        /**
        * 0: 禁止规则
        * 1: 警告
        * 2: 必须
        */
        // render不规范
        'react/display-name': 'off',
        // 变量名不正确,比如 style_id
        '@typescript-eslint/camelcase': 'off',
        // 允许any
        '@typescript-eslint/no-explicit-any': 'off',
        'react/prop-types': 'off',
        // 空函数
        '@typescript-eslint/no-empty-function': 0,
        // 函数先后顺序
        '@typescript-eslint/no-use-before-define': 'off',
        // return null
        '@typescript-eslint/ban-ts-ignore': 'off',

        'require-atomic-updates': 'off',
        '@typescript-eslint/triple-slash-reference': 'off',
        // 未使用变量
        '@typescript-eslint/no-unused-vars': 0,
        // 数组统一空格 [1, 2, 3, ...]
        'array-bracket-spacing': 2,
        // prettier 中默认函数名不加空格,类似 function add() {},而eslint中默认为function add () {}
        'space-before-function-paren': 0
      }
    })
  }
  // 在js中的常用配置方式
  const { getEslint } = require('xcc-standard-eslint')

  module.exports = {
    ...getEslint({
      ignorePatterns: ['.dll', 'build', '.temp'],
      useTs: false,
      rules: {
        'comma-dangle': 'off',
        'function-paren-newline': 'off',
        'global-require': 'off',
        'import/no-dynamic-require': 'off',
        'no-inner-declarations': 'off',
        // New rules
        'class-methods-use-this': 'off',
        'import/extensions': 'off',
        'import/prefer-default-export': 'off',
        // render不规范
        'react/display-name': 'off',
        'react/prop-types': 'off',
        'require-atomic-updates': 'off',
        // 数组统一空格 [1, 2, 3, ...]
        'array-bracket-spacing': 2,
        // prettier 中默认函数名不加空格,类似 function add() {},而eslint中默认为function add () {}
        'space-before-function-paren': 0
      }
    })
  }

.eslintignore

排除不需要执行检查的文件,一般只有src目录文件需要处理

  dist
  build
  config
  scripts
  node_modules
  public
  .babelrc
  !.*.js
  publish.js
  server.js
  version.js
  tsconfig.json
  package.json

prettier相关

prettier是一个流行的代码格式化工具的名称,它能够解析代码,使用你自己设定的规则来重新打印出格式规范的代码

  npm install xcc-standard-prettier

【prettier官网使用案例】

.prettierrc.js

  const { getPrettier } = require('xcc-standard-prettier')

  module.exports = {
    ...getPrettier()
  }

.prettierignore

排除不需要进行代码美化的文件

  .dll
  build/
  .temp
  node_modules
  .vscode

stylelint相关

stylelint是用来对css文件进行格式化及美化的,再css/less/scss中都可以使用

  npm install xcc-standard-stylelint

.stylelintrc.js

  const { getStyleLint } = require('xcc-standard-stylelint')

  module.exports = {
    ...getStyleLint({
      rules: {
        // 字体文件相关
        'font-family-no-missing-generic-family-keyword': null,
        // 空的样式文件
        'no-empty-source': null,
        // 计算属性 calc()
        'function-calc-no-invalid': null
      }
    })
  }

commit相关

用来对commit阶段效验的,比如代码,样式,commit提交文案等不符合配置的规范时,都可以终止commit的提交

  npm install xcc-commitlint husky lint-staged

.commitlintrc.js

  const { getCommitLint } = require('xcc-commitlint')

  module.exports = {
    ...getCommitLint()
  }

编辑器相关配置

该文件用来定义项目的编码规范,编辑器的行为会与.editorconfig 文件中定义的一致,并且其优先级比编辑器自身的设置要高,这在多人合作开发项目时十分有用而且必要

.editorconfig

  root = true

  [*]
  charset = utf-8
  end_of_line = lf
  indent_style = space
  indent_size = 2
  trim_trailing_whitespace = true
  insert_final_newline = true

vscode配置

  {
    "editor.formatOnSave": true
  }
  // setting.json部分相关配置
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[javascript|react]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescript|react]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[less]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[css]": {
     "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[json]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "prettier.semi": false,
  "prettier.singleQuote": true,
  "editor.formatOnType": true,
  // 设置默认使用本地配置文件规则
  "prettier.configPath": ".prettierrc.js",
  "stylelint.config": ".stylelintrc.js",
  "[jsonc]": {
    "editor.defaultFormatter": "rvest.vs-code-prettier-eslint"
  },
  "[markdown]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }

package.json中相关配置

新增了如下命令👇

package.json script

  "script": {
    ...
    "lint": "eslint . --ext .js,.jsx,.ts,.tsx --quiet",
    "lint-fix": "eslint . --ext .js,.jsx,.ts,.tsx --fix",
    "lint:style": "stylelint 'src/**/*.less' --syntax less",
    "lint-fix:style": "npm run lint:style -- --fix",
    "changelog": "conventional-changelog -p angular -i CHANGELOG.md -w -r 0",
    "changelog:create": "npm run changelog -- -s -r 0"
  }

package.json commit的配置

  "husky": {
    "hooks": {
      "pre-commit": "lint-staged",
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }
  },
  "lint-staged": {
    "*.{js,jsx,ts,tsx}": [
      "eslint --fix",
      "prettier --write",
      "git add"
    ]
  },

changelog文件

在安装了依赖包后,运行命令即可生成对应的changelog文件

项目接入

老项目接入

安装对应依赖包以及新增相关配置文件和在package.json中添加script命令

会展示不符合规范(standrad)的文件列表

会自动进行格式化及风格美化,一些字段规范等需要手动修改

会展示css不对的文件列表

自动化格式样式文件,极少部分需要手动修改

生成changelog文件,写入更新记录

  // 安装changelog包
  npm install conventional-changelog-cli

感谢大家

如果你觉得这篇内容对你有帮助的话:

  1. 点赞支持下吧,让更多的人也能看到这篇内容
  2. 觉得不错的话,也可以移步查看更多文章github issues

参考文档

eslint官网
prettier
editorconfig
vscode配置文档