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

前言

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

  • 缩进、换行、命名、结尾逗号等规则...
  • 样式文件属性的先后顺序规则
  • commit时文案,比如曾经见过git commit -m 'dddddd'等commit记录
  • 每次迭代的changelog记录
  • ...

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

  • 代码规范:包含编写时的命名,缩进规则,换行规则等...
  • 样式规范:包含css/less/scss等样式文件属性先后规则,命名
  • 文档规范:包含迭代的changelog记录,当前迭代是新增功能,还是bug修复,还是文档更新
  • 提交规范:包含提交代码时commit的规范,是什么类型的提交,文案
  • 语言配置:js/ts的环境配置
  • 编辑器配置:编辑器环境设置
  • ...

代码已上传到githubgithub

项目背景

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

打造统一规范代码插件

目的

  • 简化配置:只需安装几个指定的包即可(只是对相关三方包做了统一处理配置)
  • 方便接入:对于老项目,添加对应配置后,值需要运行几个命令就可以达到格式化代码的要求
  • 使用方便:每次编辑保存时会自动格式化代码(需要编辑器配合,后面会将vscode中的配置)

使用方式

安装相关依赖

  • eslint相关包
  npm install xcc-standard-eslint eslint-plugin-react eslint
  • prettier相关包
  npm install xcc-standard-prettier
  • stylelint相关包
  npm install xcc-standard-stylelint
  • commit相关包
  npm install xcc-commitlint husky lint-staged
  • changelog相关包
  npm install conventional-changelog-cli

eslint相关

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

  • 安装eslint相关包
  npm install xcc-standard-eslint eslint-plugin-react eslint
  • 项目根目录新建.eslintrc.js,配置👇

.eslintrc.js

  • useTs是否为typescript编写,默认false
  • ignorePatterns需要排除的风格转换文件夹
  • rules自定义配置规则,可以用来覆盖默认规则

  // 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是一个流行的代码格式化工具的名称,它能够解析代码,使用你自己设定的规则来重新打印出格式规范的代码

  • 安装prettier相关包
  npm install xcc-standard-prettier
  • prettier格式化后的效果

【prettier官网使用案例】

  • 项目根目录新建.prettierrc.js,配置👇

.prettierrc.js

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

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

.prettierignore

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

  .dll
  build/
  .temp
  node_modules
  .vscode

stylelint相关

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

  • 安装stylelint相关包
  npm install xcc-standard-stylelint
  • 项目根目录新建.stylelintrc.js,配置👇

.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的提交

  • 安装commit相关包
  npm install xcc-commitlint husky lint-staged
  • 项目根目录新建.commitlintrc.js,配置👇

.commitlintrc.js

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

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

编辑器相关配置

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

  • 项目根目录新建.editorconfig.js,配置👇

.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配置

  • 在vscode中安装eslintprettier对应的插件
  • 打开vscode配置文件setting.json

    mac系统下command+,,打开编辑器设置界面,输入框输入setting,打开下面的setting.json文件

  • 设置代码在保存时自动格式化
  {
    "editor.formatOnSave": true
  }
  • 设置资源文件.js .ts .jsx .tsx .less .css .scss .json格式文件都采用prettier插件进行格式化
  // 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中相关配置

新增了如下命令👇

  • npm run lint: 检查语法等格式,规范不对的js/ts文件
  • npm run lint-fix: 检查规范不对的文件并修复(语法问题需要手动修复)
  • npm run lint:style: 列出样式文件风格问题(lint:style中文件需要根据使用的是less或者scss来换)
  • npm run lint-fix:style: 格式化样式文件
  • npm run changelog: 列出每次提交的changelog记录
  • npm run changelog:create: 生成changelog文件

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文件

  • build:主要目的是修改项目构建系统(例如 glup,webpack,rollup 的配置等)的提交
  • ci:主要目的是修改项目继续集成流程(例如 Travis,Jenkins,GitLab CI,Circle等)的提交
  • docs:文档更新
  • feat:新增功能
  • feature:新增功能
  • fix:bug 修复
  • bugfix:bug 修复
  • perf:性能优化
  • refactor:重构代码(既没有新增功能,也没有修复 bug)
  • style:不影响程序逻辑的代码修改(修改空白字符,补全缺失的分号等)
  • test:新增测试用例或是更新现有测试
  • revert:回滚某个更早之前的提交
  • chore:不属于以上类型的其他类型(日常事务)

项目接入

老项目接入

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

  • npm run lint

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

  • npm run lint-fix

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

  • npm run lint:style

会展示css不对的文件列表

  • npm run lint-fix:style

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

  • npm run changelog:create

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

  // 安装changelog包
  npm install conventional-changelog-cli
  • 没有commit类型
  • commit类型错误
  • commit类型正确

感谢大家

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

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

参考文档

eslint官网

prettier

editorconfig

vscode配置文档

posted @ 2020-12-31 01:08  小菜菜爱吃菜  阅读(575)  评论(0编辑  收藏  举报