跳至主要內容

代码规范

俞文健大约 1 分钟

prettier

安装 prittier 及相关插件。

npm install prettier eslint-config-prettier eslint-plugin-prettier --D

配置 eslint。

/* .eslintrc.cjs */

module.exports = {
  // ...
  extends: [
    // ...
    "plugin:prettier/recommended"
  ]
}

配置命令。

/* package.json */

{
  // ...
  "scripts": {
    "format": "prettier --write 'src/**/*.+(js|ts|jsx|tsx)'"
  }
}

配置 prittier。

/* .prettierrc.js */

/**
 * @type {import("prettier").Config}
 */
const config = {
  // 箭头函数只有一个参数时,省略括号
  arrowParens: "avoid",
  // 括号内不出现空格
  bracketSameLine: false,
  // 对象中的空格 默认 true,true: { foo: bar },false: {foo: bar}
  bracketSpacing: true,
  endOfLine: "auto",
  // 在jsx中把 '>' 是否单独放一行
  jsxBracketSameLine: false,
  printWidth: 240,
  // 换行方式
  proseWrap: "preserve",
  // 分号
  semi: false,
  // 单引号
  singleQuote: false,
  // 缩进
  tabWidth: 2,
  // 使用 tab 缩进
  useTabs: false,
  // 行尾逗号,默认 none,可选 (none | es5 | all),es5 包括 es5 中的数组、对象,all 包括函数对象
  trailingComma: "none",
  parser: "typescript"
}

export default config

husky

git commit 之前执行自定义命令(hook)。

安装 husky。

npm install husky -D

配置命令。

/* package.json */

{
  // ...
  "scripts": {
    "prepare": "husky install"
  }
}

添加 husky hook,在 commit 前执行代码规范检查。

npx husky add .husky/pre-commit "npm run lint"
npx husky add .husky/pre-commit "npm run format"
npx husky add .husky/pre-commit "git add ."

commitlint

安装 commitlint。

npm install @commitlint/config-conventional @commitlint/cli -D

配置 commitlint。

/* commitlint.config.js */

module.exports = {
  extends: ["@commitlint/config-conventional"]
}

添加 husky hook,在 commit 前执行注释规范检查。

npx husky add .husky/commit-msg 'npx --no -- commitlint --edit ${1}'

commit 注释前缀:

  • feat 新增功能

  • chore 小改动

  • fix 修复 bug

  • release 发布版本

  • style 调整代码(修改缩进、补全分号等)

  • docs 更新文档

  • build 构建工具或外部依赖的改动(webpack、npm)

  • refactor 重构代码

  • revert 版本回退

  • perf 性能优化

  • test 增加测试