前端代码规范

109 阅读3分钟

背景

当开发者处在一个协作的团队中,会遇到成员间协作配合问题。在代码管理上,代码格式规范也是一个比较常见的问题。每个人有自己书写代码的习惯,每个人有自己的标准,没有绝对的对错。此时如果有并行的开发需求,修改到某些通用代码,格式不同往往会导致代码冲突产生,对于初级接触编程的开发者,没有工具辅助的情况下往往无法独自解决冲突。在需求迭代的过程中,由于人员的流动、迭代任务的安排,部分代码可能需要重构、拓展,不同的代码风格也会增加阅读难度。

介绍

统一代码格式化在多人的团队中很有必要。一般可以使用同一个代码编辑工具(vscode)取项目中相同的代码格式配置,代码保存时格式化代码,或者利用git hooks 提供的钩子,在代码提交前,自动格式化。

前端规范实现

eslint

eslint中文地址(官网介绍,版本版本 v8.47)ESLint 是一个用于识别和报告在 ECMAScript/JavaScript 代码中发现的模式的工具,其目标是使代码更加一致并避免错误。

  • 安装依赖 npm init @eslint/config

image.png

JavaScript - 使用 .eslintrc.js 并导出包含你的配置的对象。

JavaScript (ESM) - 在 package.json 中指定 "type":"module" 的 JavaScript 包中运行 ESLint 时使用 .eslintrc.cjs。 请注意,ESLint 目前不支持 ESM 配置。

YAML - 使用 .eslintrc.yaml 或 .eslintrc.yml 来定义配置结构。

JSON - 使用 .eslintrc.json 定义配置结构。 ESLint 的 JSON 文件也允许 JavaScript 样式的注释。

package.json - 在你的 package.json 文件中创建一个 eslintConfig 属性并在那里定义你的配置。

  • 校验文件规范
{
        strict: ['error', 'never'],
        'react/display-name': 0,
        'react/jsx-props-no-spreading': 0,
        'react/state-in-constructor': 0,
        'react/static-property-placement': 0,
        // Too restrictive: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/destructuring-assignment.md
        'react/destructuring-assignment': 'off',
        'react/jsx-filename-extension': 'off',
        'react/no-array-index-key': 'warn',
        'react-hooks/rules-of-hooks': 'error',
        'react-hooks/exhaustive-deps': 'warn',
        'react/require-default-props': 0,
        'react/jsx-fragments': 0,
        'react/jsx-wrap-multilines': 0,
        'react/prop-types': 0,
        'react/forbid-prop-types': 0,
        'react/sort-comp': 0,
        'react/react-in-jsx-scope': 0,
        'react/jsx-one-expression-per-line': 0,
        'generator-star-spacing': 0,
        'function-paren-newline': 0,
        'sort-imports': 0,
        'class-methods-use-this': 0,
        'no-confusing-arrow': 0,
        'linebreak-style': 0,
        // Too restrictive, writing ugly code to defend against a very unlikely scenario: https://eslint.org/docs/rules/no-prototype-builtins
        'no-prototype-builtins': 'off',
        'unicorn/prevent-abbreviations': 'off',
        // Conflict with prettier
        'arrow-body-style': 0,
        'arrow-parens': 0,
        'object-curly-newline': 0,
        'implicit-arrow-linebreak': 0,
        'operator-linebreak': 0,
        'no-param-reassign': 2,
        'space-before-function-paren': 0,
        'react/self-closing-comp': 1,
        'react/jsx-key': 1,
    }

Prettier

{
    "singleQuote": true,
    "tabWidth": 4,
    "semi": true,
    "singleAttributePerLine": true
}
  • vscode 保存自动格式化

    安装插件(prettier)

image.png

通过 VSCode -> 首选项 -> 设置,找到右上方打开设置图标(json) , 可配置 VSCode 编辑器的默认格式化工具,也可根据语言设置其对应的默认格式化工具。

image.png

安装依赖(注意本地node版本与npm包的匹配)

npm install prettier husky -D

运行命令

npx mrm@2 lint-staged

运行完成后,工程根目录会生成.husky文件夹,package.json会有lint-staged配置,在lint-staged下配置需要格式化的文件格式。