一份最简单的代码规范

197 阅读2分钟

本文已参加「信任创作礼」活动,一起开启掘金创作之路。

大家在项目中经常会用到代码规范的困扰,第一时间想到的都是eslint和git的husky去规定各位开发人员的规范,掘金上也有很多大佬分享相关的内容。

分享并记录一下我的项目中常用的eslint、stylelint和git husky的配置,该配置用了腾讯的eslint config。

根据项目需要可自行修改eslint、stylelint的规则,达到得心应手的状态(当然,最得心应手的就是没有规则😂)

eslint、gitLint配置

1、项目根目录创建 .eslintrc.js, commitlint.config.js, stylelint.config.js, .editorconfig 文件

1.1 eslintrc.js

module.exports = {
  root: true,
  env: {
    node: true,
    browser: true,
  },
  extends: ["eslint-config-tencent", "plugin:vue/essential"],
  rules: {
    quotes: 0,
    "no-new": 0,
    "new-cap": 0,
    "no-console": process.env.NODE_ENV === "production" ? "error" : "off",
    "no-debugger": process.env.NODE_ENV === "production" ? "error" : "off",
    "max-len": ["error", { code: 500 }],
  },
  plugins: ["vue"],
  parserOptions: {
    parser: "babel-eslint",
  },
  overrides: [
    {
      files: ["*.vue"],
      rules: {
        indent: 2,
        "vue/html-indent": [2, 2],
        "vue/return-in-computed-property": 1,
        "vue/order-in-components": 2,
        "vue/component-name-in-template-casing": [2, "kebab-case"],
        "vue/require-default-prop": 0,
      },
    },
  ],
};
​

1.2 commitlint.config.js

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

1.3 stylelint.config.js

module.exports = {
  extends: "stylelint-config-standard",
  rules: {
    "no-descending-specificity": null,
    "at-rule-no-unknown": null,
    "property-no-unknown": null,
    "selector-pseudo-class-no-unknown": null,
  },
};
​

1.4 .editorconfig

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

安装 eslint 及插件

npm i @babel/eslint-parser@^7.14.3 @commitlint/cli@^12.1.4 @commitlint/config-conventional@^12.1.4 eslint@^7.27.0 eslint-config-tencent@^1.0.0 husky@^6.0.0 @babel/eslint-parser@^7.14.3 eslint-plugin-vue@^7.9.0 stylelint@^13.13.1 stylelint-config-standard@^22.0.0 -D

初始化 husky 配置

# cd ${项目根目录}
npx husky install
# 添加 pre-commit 以及 commit-msg hook
npx husky add .husky/pre-commit "npm run lint && npm run styleLint && git add ."
npx husky add .husky/commit-msg "npx --no-install commitlint --edit $1"

添加 package scripts

# 往 package.json scripts 字段中添加下面的内容
"lint": "eslint --ext .vue,.js,.ts,.tsx ./ --max-warnings 0 --fix",
"styleLint": "stylelint **/*.{css,scss,sass,less,vue} --fix"

附录:git commit规则

在git commit的时候会校验commit的内容,可以根据以下关键词填写(也可自行百度~)

类型说明
featnew feature,新的功能
fixbug fix,bug修复
refactor代码重构,没有功能修改
optimize性能优化、增加日志打点等,没有功能修改
style代码格式修改,没有任何代码语义的变化
doc文档、注释修改
test添加或者修改测试用例,没有线上代码修改
build发布新版本、pom 修改、等构件发布,没有线上代码修改
revert之前提交的revert,由 git revert 命令生成
WIPWork In Progress,还没有完成的功能,为了尽可能让提交保持合适的大小