# 前端编码规范

## 半城云前端开发规范

### 前言

这里只列出半城云特殊约定的规范、或者是 `eslint`、`prettier` 难以限制的规则。其它未提及的可参考[airbnb javascript 代码规范](https://github.com/airbnb/javascript)。

## 组件

### 文件大小限制

单文件不能超过 600 行，若超过应进行拆分。

### 组件编写顺序

1. 常量、变量、hooks 函数 (按照相关性)
2. 工具函数、事件处理函数
3. render

```jsx
// 正例
const [visible, setVisible] = useState < boolean > false;

const [submitting, setSubmitting] = useState(false);
const handleSubmit = async (values: LoginParamsType) => {
  setSubmitting(true);
};

const { status } = data;
return <div className={styles.container}>{status}</div>;
```

### 事件处理函数

建议使用 handleSomething 命名形式，以及按照逻辑顺序排序

```jsx
// 正例
const handleStep1 = () => {};
const handleStep2 = () => {};

return (
  <>
    <button onClick={handleStep1}>第1步</button>
    <button onClick={handleStep2}>第2步</button>
  </>
);

// 反例
const step2 = () => {};
const step1 = () => {};

return (
  <>
    <button onClick={step1}>第1步</button>
    <button onClick={step2}>第2步</button>
  </>
);
```

### 属性书写规范

1. 小驼峰命名
2. 布尔值为 true 可省略
3. 事件放在最后

```jsx
// 正例
<Button loading htmlType="submit" onClick={() => {}}>
  btn
</Button>

// 反例
<Button loading={true} onClick={() => {}} htmltype="submit">
  btn
</Button>
```

### 尽量不要手动操作 DOM

尽量（不到万不得已）不要手动操作 DOM，包括：增删改 dom 元素、以及更改样式、添加事件等。

## css

### 属性顺序

1. 展示类型及文档流相关/Display & Flow
2. 定位信息/Positioning
3. 边距/Margins, Padding
4. 元素尺寸/Dimensions
5. 边框/Borders, Outline
6. 文字排版/Typographic Styles
7. 背景/Backgrounds
8. 其他如透明度，光标样式及衍生内容/Opacity, Cursors, Generated Content

```css
/* 正例 */
display: inline-block;
position: releative;
margin: 1em 0;
padding: 1em 4em;
width: 100px;
height: 100px;
font-size: 3em;
font-family: Avenir, Helvetica, Arial, sans-serif;
text-align: center;
text-transform: uppercase;
text-decoration: none;
color: #fff;
background: #196e76;
border: 0.25em solid #196e76;
box-shadow: inset 0.25em 0.25em 0.5em rgba(0, 0, 0, 0.3), 0.5em 0.5em 0 #444;
```

### 不建议单一属性类

无太大意义，而且要写较多类名，以及无法获得编辑器补全提示。

```css
/* 反例 */
.font-weight-400 {
  font-weight: 400;
}
.font-weight-500 {
  font-weight: 500;
}
.font-weight-600 {
  font-weight: 600;
}
```

### 约定前缀

bem 命名方式进行样式隔离时，可参考以下类名前缀 全局: g- 页面: p- 组件: c-

## git

### 不建议忽略 package-lock.json

无法锁定版本，依赖版本不一致可能导致问题

### rebase 代替 merge

## html

### 语义化标签

HTML5 中新增很多语义化标签，所以优先使用语义化标签，避免一个页面都是 div 或者 p 标签

```markup
<!-- 正例 -->
<header></header>
<footer></footer>

<!-- 反例 -->
<div>
  <p></p>
</div>
```

## js

### 避免名称冗余

```javascript
// 正例
const car = {
  make: "Honda",
  model: "Accord",
  color: "Blue",
};

// 反例
const car = {
  carMake: "Honda",
  carModel: "Accord",
  carColor: "Blue",
};
```

### 命名适用动词+名词形式

```javascript
// 正例
const getData = () => {};

// 反例
const dataGet = () => {};
```

### 命名严谨性

代码中的命名严禁使用拼音与英文混合的方式，更不允许直接使用中文的方式。注意词性、单复数、时态等的准确表达。 说明：正确的英文拼写和语法可以让阅读者易于理解，避免歧义。注意，即使纯拼音命名方式也要避免采用。

正例：`henan / luoyang / rmb 等国际通用的名称，可视同英文。`

反例：`DaZhePromotion [打折] / getPingfenByName() [评分] / int 某变量 = 3`

### 杜绝完全不规范的缩写，避免望文不知义

反例：AbstractClass“缩写”命名成 AbsClass；condition“缩写”命名成 condi，此类随意缩写严重降低了代码的可阅读性。

### 不同逻辑、不同语义、不同业务的代码之间插入一个空行分隔开来以提升可读性

说明：任何情形，没有必要插入多个空行进行隔开。

### 使用字面值创建对象

```javascript
// 正例
let user = {};

// 反例
let user = new Object();
```

### 使用 ES6,7

必须优先使用 ES6,7 中新增的语法糖和函数。这将简化你的程序，并让你的代码更加灵活和可复用。

> 必须强制使用 ES6, ES7 的新语法，比如箭头函数、await/async ， 解构， let ， for...of 等等

### 条件判断和循环最多三层

条件判断能使用三目运算符和逻辑运算符解决的，就不要使用条件判断，但是谨记不要写太长的三目运算符。如果超过 3 层请抽成函数，并写清楚注释。

## 其它

### 文件引用

按照外部包、公共文件、绝对路径、相对路径的顺序排序

```javascript
import { Button, Divider, message, Input, Drawer } from "antd";
import React, { useState, useRef } from "react";
import { PageContainer, FooterToolbar } from "@ant-design/pro-layout";
import ProTable, { ProColumns, ActionType } from "@ant-design/pro-table";
import ProDescriptions from "@ant-design/pro-descriptions";
import test from "@/utils/utils";
import request from "../../utils/request";
import CreateForm from "./components/CreateForm";
```

另外要注意引用大小写问题，在一些对文件路径大小写敏感的系统会出问题。

### 控制台信息

留意排查项目报错或者警告信息，而不是能跑就行。

### 删除无用代码

使用了 git，对于无用代码必须及时删除，例如：一些调试的 console 语句、无用的弃用功能代码。

**附： 函数方法常用的动词:**

```javascript
get 获取/set 设置,
add 增加/remove 删除
create 创建/destory 移除
start 启动/stop 停止
open 打开/close 关闭,
read 读取/write 写入
load 载入/save 保存,
create 创建/destroy 销毁
begin 开始/end 结束,
backup 备份/restore 恢复
import 导入/export 导出,
split 分割/merge 合并
inject 注入/extract 提取,
attach 附着/detach 脱离
bind 绑定/separate 分离,
view 查看/browse 浏览
edit 编辑/modify 修改,
select 选取/mark 标记
copy 复制/paste 粘贴,
undo 撤销/redo 重做
insert 插入/delete 移除,
add 加入/append 添加
clean 清理/clear 清除,
index 索引/sort 排序
find 查找/search 搜索,
increase 增加/decrease 减少
play 播放/pause 暂停,
launch 启动/run 运行
compile 编译/execute 执行,
debug 调试/trace 跟踪
observe 观察/listen 监听,
build 构建/publish 发布
input 输入/output 输出,
encode 编码/decode 解码
encrypt 加密/decrypt 解密,
compress 压缩/decompress 解压缩
pack 打包/unpack 解包,
parse 解析/emit 生成
connect 连接/disconnect 断开,
send 发送/receive 接收
download 下载/upload 上传,
refresh 刷新/synchronize 同步
update 更新/revert 复原,
lock 锁定/unlock 解锁
check out 签出/check in 签入,
submit 提交/commit 交付
push 推/pull 拉,
expand 展开/collapse 折叠
begin 起始/end 结束,
start 开始/finish 完成
enter 进入/exit 退出,
abort 放弃/quit 离开
obsolete 废弃/depreciate 废旧,
collect 收集/aggregate 聚集
```

**附：常用的缩写:**

[常见编程命名缩写](https://blog.csdn.net/wf19930209/article/details/78577918)

## 项目

### 项目命名

全部采用小写方式， 以中划线分隔。

正例：`mall-management-system`

反例：`mall_management-system / mallManagementSystem`

### 目录命名

全部采用小写方式， 以中划线分隔，有复数结构时，要采用复数命名法

正例： `scripts / styles / components / images / utils / layouts / demo-styles / demo-scripts`

反例： `script / style / demo_scripts / demoStyles`

【特殊】react 项目中的页面、组件目录，使用大驼峰命名

正例： `HeadSearch / PageLoading`

反例： `head-search / page-loading / authorized / notice-icon`

### 项目结构

参照 ant desiagn pro

```
├── src                    源码目录
|   ├── assets             静态资源目录
|   ├── components         基础组件目录
|   ├── pages              页面文件目录
|   ├── services           公用服务接口目录
|   ├── styles             公用样式目录
|   ├── utils              公用工具目录
```

### 页面、组件结构

```
├── Login                  主目录
|   ├── components         组件
|   ├── data.ts            数据
|   ├── index.less         样式
|   ├── index.tsx          入口
|   ├── service.ts         接口
|   ├── type.d.ts          类型定义
|   ├── util.ts            工具函数
```

### 基本原则

就近原则，相关的文件放一起。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tech.banchengyun.com/docs/common/code-standards.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
