前端多人协作之代码规范

发布时间 2023-08-05 15:43:36作者: wanglei1900

代码规范

学习自并感谢 Geekers-Admin 和 Hooks-Admin 开源项目的作者 HalseySpicy

一、EditorConfig

EditorConfig 用于定义项目中的编辑器配置。可以确保团队成员在不同的编辑器中保持一致的代码风格和格式。

?EditorConfig 官网

前置

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

有些编辑器默认支持 editorConfig,如 webstorm;而有些编辑器则需要安装 editorConfig 插件,如 ATOM、Sublime、VSCode(EditorConfig for VSCode)等。

EditorConfig 的配置文件是从上往下读取的并且最近的 EditorConfig 配置文件会被最先读取. 匹配 EditorConfig 配置文件中的配置项会按照读取顺序被应用, 所以最近的配置文件中的配置项拥有优先权

配置

项目根目录下配置文件.editorconfig

# @see: http://editorconfig.org

# 设置为true表示该配置文件是根配置文件,EditorConfig将停止在父目录中查找其他配置文件
root = true

[*] # 表示所有文件适用
charset = utf-8 # 设置文件字符集为 utf-8
end_of_line = lf # 控制换行类型(换行lf | 回车cr | 回车换行crlf)
insert_final_newline = true # 始终在文件末尾插入一个新行
indent_style = tab # 缩进风格(tab | space)
indent_size = 2 # 缩进大小(字节)
max_line_length = 130 # 最大行长度

[*.md] # 表示仅 md 文件适用以下规则
max_line_length = off # 关闭最大行长度限制
trim_trailing_whitespace = false # 关闭删除行末尾空格

不同系统平台下编辑可能导致警告或者错误,比如 在 Windows 下编写的 shell 脚本,直接放到 linux/unix 下执行会出错,因为行结束符不一样。

  • Dos 和 Windows 采用回车+换行(cr+lf)来表示换行
  • UNIX 和 Linux 采用换行符(lf)来表示换行
  • MAC OS 采用回车符(cr)来表示换行

二、ESLint

ESLint 是一个可配置的 JavaScript 代码检查工具。可以帮助您发现和修复代码中的潜在问题,如语法错误、潜在的运行时错误、不符合最佳实践的代码等。ESLint 的目标是帮助开发者编写更高质量、更一致的 JavaScript 代码。

?ESLint 官网

忽略

项目根目录下配置忽略检查文件.eslintignore

*.sh
node_modules
*.md
*.woff
*.ttf
.vscode
.idea
dist
/public
/docs
.husky
.local
/bin
/src/mock/*
stats.html

配置项

项目根目录下配置文件.eslintrc.cjs

// @see: https://zh-hans.eslint.org

module.exports = {
  // 设置为true表示该配置文件是根配置文件,ESLint将停止在父目录中查找其他配置文件。
  root: true,
  // 指定脚本运行的环境,可以是浏览器、Node.js或ES6等。这些环境会提供一组预定义的全局变量。
  env: {
    browser: true,
    node: true,
    es6: true
  },
  /* 配置一些特定的设置,例如React的版本 */
  settings: {
    react: {
      version: "detect"
    }
  },
  /* 指定用于解析代码的解析器,这里使用的是@typescript-eslint/parser,它可以解析TypeScript代码。 */
  parser: "@typescript-eslint/parser",
  /* 配置解析器的选项,例如指定ECMAScript版本、源代码类型和JSX的pragma。 */
  parserOptions: {
    ecmaVersion: "latest",
    sourceType: "module",
    jsxPragma: "React",
    ecmaFeatures: {
      jsx: true
    }
  },
  /*  指定要使用的插件,这里使用了React、TypeScript和Prettier插件。 */
  plugins: ["react", "@typescript-eslint", "prettier"],
  /*  扩展现有的规则集,这里使用了一些推荐的规则集 */
  extends: [
    "eslint:recommended",
    "plugin:react/jsx-runtime",
    "plugin:react-hooks/recommended",
    "plugin:prettier/recommended",
    "plugin:@typescript-eslint/recommended"
  ],
  /* 配置具体的规则 */
  rules: {
    // eslint (http://eslint.cn/docs/rules)
    "no-var": "error", // 设置为"error",要求使用let或const代替var关键字。
    "no-multiple-empty-lines": ["error", { max: 1 }], // 禁止出现多个空行。
    "no-use-before-define": "off", // 允许在定义之前使用函数、类或变量。
    "prefer-const": "off", // 设置为"off",该规则旨在标记使用let声明但从未重新赋值的变量,建议使用const代替。
    // typeScript (https://typescript-eslint.io/rules)
    "@typescript-eslint/no-unused-vars": "error", // 设置为"error",禁止未使用的变量。
    "@typescript-eslint/prefer-ts-expect-error": "error", // 设置为"error",禁止使用@ts-ignore注释。
    "@typescript-eslint/ban-ts-comment": "error", //  设置为"error",禁止使用@ts-<directive>注释或在指令后添加描述。
    "@typescript-eslint/no-inferrable-types": "off", // 设置为"off",允许使用可以轻松推断的显式类型,以避免不必要的冗余。
    "@typescript-eslint/no-namespace": "off", // 设置为"off",允许使用自定义的TypeScript模块和命名空间。
    "@typescript-eslint/no-explicit-any": "off", // 设置为"off",允许使用any类型。
    "@typescript-eslint/ban-types": "off", // 设置为"off",允许禁止特定类型。
    "@typescript-eslint/no-var-requires": "off", // 设置为"off",允许在导入语句中使用require语句。
    "@typescript-eslint/no-empty-function": "off", // 设置为"off",允许空函数。
    "@typescript-eslint/no-non-null-assertion": "off", // 设置为"off",允许使用非空断言后缀操作符!。
    // react (https://github.com/jsx-eslint/eslint-plugin-react)
    "react-hooks/rules-of-hooks": "error", // 设置为"error",确保在组件或自定义钩子中调用Hooks。
    "react-hooks/exhaustive-deps": "off" // 设置为"off",不需要对useEffect和useCallback的依赖项进行详尽检查。
  }
};

三、Prettier

Prettier 是一个代码格式化工具,专注于调整代码的格式,如缩进、换行、引号等。以确保代码的一致性和可读性。与 ESLint 不同,Prettier 主要关注代码的格式化而不是语法问题。

?Prettier 官网

忽略

项目根目录下配置忽略检查文件.prettierignore

/dist/*
.local
/node_modules/**

**/*.svg
**/*.sh

/public/*
stats.html

配置项

项目根目录下配置文件.prettierrc.cjs

// @see: https://www.prettier.cn
module.exports = {
  /* 指定最大行长度 */
  printWidth: 130,
  /* 指定缩进的空格数或制表符数 */
  tabWidth: 2,
  /* tabs缩进 (true: tabs | false: spaces) */
  useTabs: false,
  /* 语句末尾使用分号 (true: yes | false: no) */
  semi: true,
  /* 字符串中使用双引号 (true: 单引号 | false: 双引号) */
  singleQuote: false,
  /* 对象字面量中的属性名称周围使用引号 (as-needed: 需要 | consistent: 保持一致性 | preserve:保留原样) */
  quoteProps: "as-needed",
  /* JSX中使用双引号 (true: 单引号, false: 双引号)  */
  jsxSingleQuote: false,
  /* 多行对象和数组的末尾添加尾逗号(none:不添加尾随逗号 | es5: ES5 语法支持的情况下,添加尾随逗号 | all:所有可能的地方都添加尾随逗号(包括函数参数) ) */
  trailingComma: "none",
  /* 对象字面量和数组中的大括号之间添加空格,eg."{ foo: bar }" (true: yes | false: no) */
  bracketSpacing: true,
  /* 将JSX元素的 尖括号 > 放在最后一行的末尾而不是新的一行  (true: 行末尾 | false: 另起一行) */
  bracketSameLine: false,
  /* 箭头函数的单个参数省时略参数括号 (avoid: 省略 | always: 不省略括号) */
  arrowParens: "avoid",
  /* 在文件开头包含@prettier  (true: yes | false: no) */
  requirePragma: false,
  /* 文件顶部插入特殊的@format标记  (true: yes | false: no)  */
  insertPragma: false,
  /* 保持文本的换行 (preserve: 不换行 | always: 始终换行 | never: 永不换行 | minimal: 最小化换行 ) */
  proseWrap: "preserve",
  /* 控制在 HTML 中处理空格敏感度的行为 (css:据 CSS 语法规则决定 HTML 标签之间的空格格式 | strict: HTML 标签之间保持严格的空格处理 | ignore: 忽略 HTML 标签之间的空格处理) */
  htmlWhitespaceSensitivity: "css",
  /* 定义换行符的类型 (auto:自动选择适当的换行符类型 | lf:强制使用 LF(\n)作为行末换行符 | crlf:强制使用 CRLF(\r\n)作为行末换行符 | cr:强制使用 CR(\r)作为行末换行符 ) */
  endOfLine: "auto",
  /* 格式化的代码的起始 */
  rangeStart: 0,
  rangeEnd: Infinity
};

四、Stylelint

Stylelint 是一个静态分析 CSS 代码、查找问题、强制执行代码风格规则的工具。

?Stylelint 官网

忽略

项目根目录下配置忽略检查文件.stylelintignore

/dist/*
/public/*
public/*
stats.html

项目根目录下配置文件.stylelintrc.cjs

配置项

// @see: https://stylelint.nodejs.cn

module.exports = {
  // 指定此配置文件为根配置文件,不向上查找其他配置文件。
  root: true,
  // extends:通过扩展配置,继承了两个规则集:
  extends: [
    // 使用了 stylelint 的官方标准规则集,包含一些常见的代码风格规则。
    "stylelint-config-standard",
    // 使用了 stylelint 的属性排序插件规则集,用于强制执行 CSS 属性的书写顺序。
    "stylelint-config-recess-order"
  ],
  // overrides:针对特定文件类型进行配置覆盖的部分。
  overrides: [
    // "**/*.html":对所有的 .html 文件进行配置。
    {
      files: ["**/*.html"],
      customSyntax: "postcss-html"
    },
    // "**/*.less":对所有的 .less 文件进行配置。
    {
      files: ["**/*.less"],
      customSyntax: "postcss-less"
    }
  ],
  rules: {
    /* URL 的引号规则  (always: 始终 | never: 从不 | consistent: 一致) */
    "function-url-quotes": "always",
    /* 16 进制颜色值的写法 (short: "#f00" | long: "#ff0000" ) */
    "color-hex-length": "long",
    /* 规则前是否要求空行  (always: 有空行 | never: 无空行 | always-multi-line: 多行规则有空行 | never-multi-line: 多行规则无空行 ) */
    "rule-empty-line-before": "never",
    /* 是否缺少通用字体系列关键字  (true: 开启 | null: 关闭 ) */
    "font-family-no-missing-generic-family-keyword": null,
    /* 不允许空的样式源的规则  (true: 开启 | null: 关闭 ) */
    "no-empty-source": null,
    /* 选择器类名的格式规则  (regex|string) */
    "selector-class-pattern": null,
    /* 不允许使用特定厂商的前缀,例如 -webkit- (true: 开启 | null: 关闭 ) */
    "value-no-vendor-prefix": null,
    /* 不允许具有较低优先级的选择器出现在较高优先级的选择器之后的规则 (true: 开启 | null: 关闭 )  */
    "no-descending-specificity": null,
    /* 允许自定义 CSS 变量名称的规则 (regex|string) */
    "custom-property-pattern": null,
    /* 媒体特性区间表示法的规则 (context|prefix) */
    "media-feature-range-notation": null,
    /* 伪类选择器的规则,允许忽略指定的伪类 */
    "selector-pseudo-class-no-unknown": [
      true,
      {
        ignorePseudoClasses: ["global"]
      }
    ]
  },
  /* 指定要忽略的文件的模式 */
  ignoreFiles: ["**/.js", "/*.jsx", "/.tsx", "**/.ts"]
};

五、团队协作风格统一 .vscode 文件

根目下.vscode 文件 存储的是编译器相关。

.vscode/extensions.json

项目根目录下.vscode 文件下 extensions.json 为项目下推荐安装插件

如果,你的.vscode 下的 extensions.json,编译器会自动安装相应的扩展 ID,团队协作必备。
vscode 主侧栏的 扩展里输入@recommended,可以查看当前当前扩展推荐,命名规则为"作者名字.插件名字"。
如果想往里添加新的扩展推荐,可以去插件库主页小齿轮处复制扩展 ID。

{
  "recommendations": [
    "dsznajder.es7-react-js-snippets",
    "dbaeumer.vscode-eslint",
    "stylelint.vscode-stylelint",
    "esbenp.prettier-vscode",
    "editorconfig.editorconfig",
    "streetsidesoftware.code-spell-checker",
    "mikestead.dotenv"
  ]
}

.vscode/settings.json

项目根目录下.vscode 文件下 setting.json 为 vscode 编辑器和插件的配置。

{
  // 在保存文件时自动进行代码格式化。
  "editor.formatOnSave": true,
  // 在保存文件时,针对样式文件使用 stylelint 进行自动修复。
  "editor.codeActionsOnSave": {
    "source.fixAll.stylelint": true
  },
  // 启用 stylelint 插件以进行样式代码的静态检查
  "stylelint.enable": true,
  // 指定需要被 stylelint 验证的文件类型
  "stylelint.validate": ["css", "less", "postcss", "scss", "sass", "html"],
  // 设置文件的行尾格式为换行符 \n
  "files.eol": "\n",
  // 对于不同的文件类型,配置了默认的格式化,使用 prettier 作为默认的代码格式化工具。
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[json]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[jsonc]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[scss]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[html]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[markdown]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[less]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  // 拼写检查
  "cSpell.words": [
		"..."
  ]
}