一些团队内快速code review的点,持续记录中

154 阅读2分钟

命名规范

typescript-eslint.io/rules/namin…

命名使用正确的英文单词拼写

可以安装vscode插件 Code Spell Checker

// Yes  
const loyalTNumber = '112233'// No  
const loyalTnumber = '112233';

变量使用驼峰命名

// Yes
const errorMessage = 'error message';
// No
const errormessage = 'error message';

TS类型、枚举命名使用大驼峰

interface Props {  
    className: string;  
}  
  
type Gender = 'Miss' | 'Mr';  
  
enums State {  
    Success'success',  
    Failed'failed'  
}

文件、文件夹命名使用中划线分割

书写规范

尽可能删掉无用的代码注释,特殊情况注明原因和负责人 React组件尽可能使用 function component react判断渲染为空时

// Yes  
{true ? <div>content</div> : null}  
  
{true && <div>content</div>}  
  
// No  
{true ? <div>content</div> : <></>}  
  
// No  
{true ? <div>content</div> : <Fragment></Fragment>}

为空渲染提前 return,可读性更强

    if (isEmpty(data)) {  
        return null  
    }  
    return <div>render content here</div>

使用tailwind css处理响应式差异时,需要用classNames库套一层,让属性一一对应

<div className={classNames('text-black', 'w-4 h-4', 'xl:w-4.5 xl:h-4.5')}></div>

使用includes代替indexOf

const flag1 = ['A''B'].indexOf('A') > -1;
// includes更清晰明了
const flag2 = ['A''B'].includes('A');

尽可能使用单文件组件 一个文件中只写一个组件 没有children的组件使用单标签写法

// yes  
<Image />  
  
// No  
<Image></Image>

使用lodash isEmpty判断数据是否存在

{brandList.length > 0 ? (<div />): (<div>empty</div>)}  
  
{!isEmpty(brandList) ? (<div />): (<div>empty</div>)}

多语言中如果遇到变量的情况,统一使用插值处理

// 多语言转换  
{t('nameMaxLength', { max20 })}  
  
// 多语言配置  
{  
    nameMaxLength"名称不能超过{{max}}个字符"  
}

代码引入规范

github.com/import-js/e… 按资源类型排序:js > img > css

可以安装vscode插件 ES6 Import Formatter

import React from 'react';  
import { classNames } from '@/services';  
import bg from '@/resources/images/common/pc-bg.png';  
import styles from './index.module.scss';

按路径层次排序:第三方资源 > 内部公共资源 > 相对路径资源 不同类型的资源之间留一个空行

import React from 'react';
import { useLocalObservable } from 'mobx-react';
// 这里留空行
import { classNames } from '@/services';
import { CommonApi } from '@/api';

默导出认模块别名规范,列举一些常用包的引入规范 import classNames from 'classnames'; lodash 从 lodash-es 库中导入 import { get } from 'lodash-es';

TBC

引用同级目录下的公共组件有以下两种写法

import Text from '../text';  
import Touchable from '../touchable';  
// VS  
import { TextTouchable } from '@/components';

Promise catch的不同写法

Promise.then(
    (res) => {
        
    }, (e) => {
        
    }
)

Promise
.then((res) => {})
.catch((e) => {})

条件渲染不同的写法

{ needRender ? (<div>content</div>) : (<React.Fragment />)}

{ needRender ? ( <div>content</div> ) : (<></>)}

{ needRender ? (<div>content</div>) : null}

{ needRender && (<div>content</div>)}

数组泛型的不同写法

Array<T>
// VS
T[]

// api文件定义
// const XXApi = {}