Web 端代码规范

目录

1、代码规范概述

2、代码规范流程搭建

3、代码规范细则

1、代码规范概述

良好的代码规范能够提供软件的可读性、可维护性,降低开发成本和提高开发效率。

2、代码规范流程搭建

代码规范自动化检测流程大致思路如下:

  • 开发人员开发提交代码到版本库时,触发事先配置好的 commit hook;
  • commit hook 运行代码规范检测脚本;
  • 前端 linter 工具将遍历目标文件夹,识别代码中不符合规范部分并将一部分进行自动更正,将剩余需要手动修复部分展示给开发者;
  • 开发者修复代码后继续走上述流程直至代码符合规范为止;
  • 此时提交到版本库的代码就是符合规范的代码;

这里 JavaScript 使用的检测工具是 ESLint,样式使用的是 stylelint,配合 husky 和 lint-staged 打造一套自动化的代码规范检测流;

husky

husky 能在 git 不同的阶段配置 hooks,从而能够实现自动化检测代码规范的目的,以 neo 为例,在 package.json 文件中,配置 husky 属性,在代码预提交阶段运行 lint 脚本;

// package.json
  "husky": {
    "hooks": {
      "pre-commit": "npm run lint"
    }
  },

仅使用 husky 在提交代码时会检查所有文件,我们预期是仅仅检查增量文件,因此配合 lint-staged,它只会检查我们通过 git add 添加到暂存区的文件;

// package.json
  "lint-staged": {
    "src/**/*.{ts,tsx}": [
      "eslint --fix", "git add"
    ],
    "src/**/*.{scss,css}": [
      "stylelint --fix", "git add"
    ]
  },

ESLint

JavaScript 代码规范详情见下,neo 项目的基本规则集继承 typescript-eslint 和 react-app,并结合自身项目特点对其部分规则进行调整以及增加团队内部代码规约;

3、代码规范细则

JavaScript

缩进(Indent)

缩进 2 个空格

// good
const bool = true;
if (bool) {
  console.log("right");
}

// bad
const bool = true;
if (bool) {
    console.log("right");
}

尾随分号

JS 是可选分号语言,分号可加可不加,视乎团队的编码习惯,这里参照 C-like 风格,统一采用尾随分号;

// good
const done = 1;

// bad
const undo = 0

尾随逗号

尾随逗号好处是使 git 扩展差异更加清洁,并且在对象添加新属性时更方便和减少错误,这里要求对象强制尾随逗号;

// bad - 没有尾随逗号的 git 差异
const hero = {
     firstName: 'Florence',
-    lastName: 'Nightingale'
+    lastName: 'Nightingale',
+    inventorOf: ['coxcomb chart', 'modern nursing']
};

// good - 有尾随逗号的 git 差异
const hero = {
     firstName: 'Florence',
     lastName: 'Nightingale',
+    inventorOf: ['coxcomb chart', 'modern nursing'],
};

换行

  • 不同类型语句换行
// good
const cat = 1;
const mouse = 2;

if (cat !== mouse) {
  console.log("not like a mouse");
}

// bad
const cat = 1;
const mouse = 2;
if (cat !== mouse) {
  console.log("not like a mouse");
}
  • 三目运算符换行规则

少于 30 个字符可单行;
超过 30 个字符应遵循以下折行规则;

// good
const score = 90;
const isExcellent = score >= 90 ? true : false;

// not bad
const score = 90;
const isExcellent = score >= 90 ? true : false;

// bad
const score = 90;
const rate =
  score >= 90 ? "good" : score < 90 && score >= 80 ? "not bad" : "not good";
  • 单行字符长度不超过 140 个

console

不得将 console 相关代码提交到版本库

注释

简短注释单行显示,不建议尾随注释;

// good
// 这是一个变量赋值语句
let a = 1;

// bad
let b = 2; // 这是一个变量赋值语句

对于需要详细说明的代码逻辑,使用多行注释

/*
 * 这里是个多行注释,将会有很多行。
 * 大伙凑活着看哈~~~
 */
let c = 3;

对于待编写的代码块,需要使用 @todo 进行标注,并写明待完善的逻辑内容;

class Example extends React.Component {
  async getDataList = (params = {}) => {
    // @todo 待接入获取商品列表接口
    // const res = await this.$api.product.getProductList(params)
  }
}

变量命名

  • 避免单字母命名
// bad
function q() {
  // ...
}

// good
function query() {
  // ...
}
  • 在命名对象、函数和实例时使用驼峰命名法
// bad
const OBJEcttsssss = {};
const this_is_my_object = {};
function c() {}

// good
const thisIsMyObject = {};
function thisIsMyFunction() {}
  • 只有在命名构造器或者类的时候才用帕斯卡拼命名法
// bad
function user(options) {
  this.name = options.name;
}

const bad = new user({
  name: 'nope',
});

// good
class User {
  constructor(options) {
    this.name = options.name;
  }
}

const good = new User({
  name: 'yup',
});

空白

  • 不要在块的开头使用空白行
// bad
function bar() {

  console.log(foo);

}

// bad
if (baz) {

  console.log(qux);
} else {
  console.log(foo);

}

// bad
class Foo {

  constructor(bar) {
    this.bar = bar;
  }
}

// good
function bar() {
  console.log(foo);
}

// good
if (baz) {
  console.log(qux);
} else {
  console.log(foo);
}
  • 不要在括号、中括号内添加空格
// bad
function bar( foo ) {
  return foo;
}

// good
function bar(foo) {
  return foo;
}

// bad
if ( foo ) {
  console.log(foo);
}

// good
if (foo) {
  console.log(foo);
}

// bad
const foo = [ 1, 2, 3 ];
console.log(foo[ 0 ]);

// good
const foo = [1, 2, 3];
console.log(foo[0]);
  • 在花括号内添加空格
// bad
const foo = {clark: 'kent'};

// good
const foo = { clark: 'kent' };
  • 逗号后空格
// bad
var foo = 1,bar = 2;
var arr = [1 , 2];

// good
var foo = 1, bar = 2;
var arr = [1, 2];

更多规则待续...

参考资料

在项目中启用 ESLint 与 Stylelint 检查

lint-staged和husky在pre-commit阶段做代码检查

ESLint

Airbnb JavaScript 代码规范

Javascript编程风格

你可能感兴趣的:(Web 端代码规范)