51.ca FE team JavaScript convention
I. JavaScript Convention
本文档用于定义 51.CA 前端团队 JavaScript 源代码的代码规范. 包含了:
- 命名规范
- 代码格式
- 函数及方法规范
- etc
- Extension:
- Vanilla JavaScript:
.js
- React JSX:
.jsx
- Vue:
.vue
- Naming:
- General directory:
lowerCamelCase 小驼峰
- Vanilla JavaScript:
lowerCamelCase.js
- React JSX:
CamelCase.jsx 大驼峰
- React JSX directory: CamelCase.jsx 大驼峰
- MyComponent
|- index.js
|- MyComponent.jsx
|- MyComponent2.jsx
- Vue: camelCase.vue
- 优先使用 ES6 Module:
import
/export
- 如果没有特殊情况 Module name 必须匹配文件名, e.g:
// good:
import myFunc from 'some/package/myFunc';
// bad:
import randomName from 'some/package/myFunc';
// good:
const myModule = require('package/path/myModule.js');
// bad:
const someName = require('package/path/myModule.js');
依赖引入和具体调用之间必须有一行空行, e.g:
// good:
import myFunc from 'some/package/myFunc';
myFucn();
// bad:
import myFunc from 'some/package/myFunc';
myFunc();
JavaScript代码格式为airbnb规范基础上自定义版本
必须是: 2-space indentation
- 单目运算符不加空格
- 双目运算符以及赋值操作符左右各需空格
// good:
for (let i = 0; i < 5; i++) {
doSomeThing();
}
const someThing = shouldDo ? shouldDo : null;
字符串一般情况必须使用单引号
const myStr = 'some string';
优先使用es6的string template
const myStr1 = 'string1';
const myStr2 = 'string2';
const combineStr = `${myStr1}${myStr2}`;
// good
const myStr1 = 'string1';
// bad
const myStr1 = 'string1';
必须使用ES6标准的声明, 不使用var
// good:
let aNumber = 1;
const noChange = 'someThing';
// bad
var someValue = 111;
// good
if (someCondition) {
doSomeThing();
}
// bad
if (someCondition) doSomeThing();
if (someCondition) return;
// good
const myFunc = (arg) => {
return arg;
};
// bad
- 符合小驼峰, 或者是 ___ 开头
- 必须是有意义的, 可阅读的英文,反对掺杂汉语拼音命名
// good:
const defaultImagePath = 'path/to/image.jpg';
const fetchData = (query) => {
// do ajax or something...
};
// bad:
const morentu = 'path/to/image.jpg';
const abc = (query) => {
// do ajax or something...
};
- 类名使用大驼峰
class MyClass extends BaseClass {
// declare things...
}
/**
* 多行
*/
// 单行
/**
* Represents a book.
* @constructor
* @param {string} title - The title of the book.
* @param {string} author - The author of the book.
*/
function Book(title, author) {}
为了帮助代码风格规范化,我们使用了一些规范化工具:
- 编辑器配置: editorconfig
- Ecma标准代码规范: eslint
- 自动格式化: prettier
- css代码规范: stylelint
可在 src 目录中下载配置文件