Malunan个人博客|IT技术博客 Malunan个人博客|IT技术博客
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《JavaScript高级程序设计》
    • 《ES6 教程》
    • 《Vue》
    • 《React》
    • 《TypeScript 从零实现 axios》
    • 《Git》
    • TypeScript
    • JS设计模式总结
    • HTML
    • CSS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 脚本
  • 剪辑
关于
  • 网站
  • 常用的前端轮子
  • 工具网站
  • 软件工具
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

Lunan Ma

升职加薪搞钱~
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《JavaScript高级程序设计》
    • 《ES6 教程》
    • 《Vue》
    • 《React》
    • 《TypeScript 从零实现 axios》
    • 《Git》
    • TypeScript
    • JS设计模式总结
    • HTML
    • CSS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 脚本
  • 剪辑
关于
  • 网站
  • 常用的前端轮子
  • 工具网站
  • 软件工具
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • 技术文档

    • Git使用手册
    • Markdown使用教程
    • npm常用命令
    • 移动端兼容问题
    • 常用cmd命令
    • npm packageJson属性详解
    • yaml语言教程
    • Git修改分支名
    • javaScript-时间相加,超过24小时继续累加
    • 获取视频文件第一帧
    • 前端获取文件下载进度
    • 前端获取上传的视频图片详细信息
    • 解决拖拽时,如果元素内有input,无法选中文本的问题
    • css点击穿透
    • vue插槽传参
    • 谷歌浏览器的kiosk模式
    • 前台下载后台返的二进制文件流
    • css实现无缝切换跑马灯样式
    • 前端优化规范
      • 前言
        • 一、 代码静态检查工具
        • 二、 命名
        • 三、JS 推荐写法
    • 懒加载+无感删除list思路
  • GitHub技巧

  • Nodejs

  • 博客搭建

  • 脚本

  • 技术
  • 技术文档
MaLunan
2024-03-25
目录

前端优化规范

# 前言

为提高代码评审效率,特制定这份清单,以辅助代码评审。

# 一、 代码静态检查工具

1、 使用 eslint 工具对 javascript 代码进行检查 eslint 检查的规范继承自 eslint-config-standard 检验规则,具体的规则介绍参 照链接:https://cn.eslint.org/docs/rules/ ,这里及以下部分不再重复介绍这些 检验规则。
2、 使用 stylelint 工具对 css 样式代码进行检查 stylelint 检查的规范继承自 stylelint-config-standard 检验规则,具体的规则 介绍参照链接:https://www.npmjs.com/package/stylelint-config-standard ,这 里及以下部分不再重复介绍这些检验规则。

# 二、 命名

2.1、JS 采用 Camel Case 小驼峰式命名

推荐:

studentInfo

2.2、避免名称冗余

推荐:


const Car = { make: "Honda", model: "Accord", color: "Blue" }; 

1
2
3

不推荐:

const Car = { carMake: "Honda", carModel: "Accord", carColor: "Blue" }; 

1
2

2.3、CSS 类名命名规范

推荐:

.block__element{} 
.block--modifier{}
1
2

2.4、命名符合语义化 命名需要符合语义化,如果函数命名,可以采用加上动词前缀: 动词 含义 can 判断是否可执行某个动作 has 判断是否含有某个值 is 判断是否为某个值 get 获取某个值 set 设置某个值

推荐:

//是否可阅读 
function canRead(){ return true; } 
 
//获取姓名 
function getName{ return this.name } 

1
2
3
4
5
6

# 三、JS 推荐写法

3.1、每个常量都需命名 每个常量应该命名,不然看代码的人不知道这个常量表示什么意思。

推荐:

const COL_NUM = 10; 
let row = Math.ceil(num/COL_NUM); 
1
2

不推荐:

let row = Math.ceil(num/10);
1

3.2、推荐使用字面量 创建对象和数组推荐使用字面量,因为这不仅是性能最优也有助于节省代码量。

推荐:

let obj = { name:'tom', age:15, sex:'男' } 
1

不推荐:

let obj = {}; 
obj.name = 'tom'; 
obj.age = 15;
obj.sex = '男';
1
2
3
4

3.3、对象设置默认属性的推荐写法

推荐:

const menuConfig = { 
  title: "Order", 
  // User did not include 'body' key 
  buttonText: "Send",
  cancellable: true 
}; 
function createMenu(config) { 
  config = Object.assign({ 
    title: "Foo", 
    body: "Bar", 
    buttonText: "Baz", 
    cancellable: true 
  },
  config 
  ); 
createMenu(menuConfig);
// config now equals: 
// {title: "Order", body: "Bar", buttonText: "Send", cancellable:true}
// ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

不推荐:

const menuConfig = { 
  title: null, 
  body: "Bar",
  buttonText: null, 
  cancellable: true
}; 
 
function createMenu(config) { 
  config.title = config.title || "Foo";
  config.body = config.body || "Bar"; 
  config.buttonText = config.buttonText || "Baz"; 
  config.cancellable=config.cancellable!==undefined?config.cancellable:true; 
}
createMenu(menuConfig); 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

3.4、将对象的属性值保存为局部变量 对象成员嵌套越深,读取速度也就越慢。所以好的经验法则是:如果在函数中需要多 次读取一个对象属性,最佳做法是将该属性值保存在局部变量中,避免多次查找带来 的性能开销。

推荐:

let person = { info:{ sex:'男' } };
function getMaleSex(){ 
  let sex = person.info.sex;
  if(sex === '男'){ 
     console.log(sex) 
  }
} 
1
2
3
4
5
6
7
不推荐: 
let person = { info:{ sex:'男' } } ;
function getMaleSex(){ 
  if(person.info.sex === '男'){ 
    console.log(person.info.sex) 
  } 
} 
1
2
3
4
5
6
7

3.5、字符串转为整型 当需要将浮点数转换成整型时,应该使用Math.floor()或者Math.round(),而不是 使用parseInt()将字符串转换成数字。Math是内部对象,所以Math.floor()`其实并 没有多少查询方法和调用时间,速度是最快的。

推荐:

let num = Math.floor('1.6'); 
1

不推荐:

let num = parseInt('1.6'); 
1

3.6、函数参数 函数参数越少越好,如果参数超过两个,要使用 ES6的解构语法,不用考虑参数的顺 序。

推荐:

function createMenu({ title, body, buttonText, cancellable }) { // ... } createMenu({ title: 'Foo', body: 'Bar', buttonText: 'Baz', cancellable: true }); 
1

不推荐:

function createMenu(title, body, buttonText, cancellable) { // ... }
1

3.7、使用参数默认值 使用参数默认值 替代 使用条件语句进行赋值。

推荐:

function createMicrobrewery(name = "Hipster Brew Co.") { // ... } 
1

不推荐:

function createMicrobrewery(name) { 
  const breweryName = name || "Hipster Brew Co."; 
  // ... 
}
1
2
3
4

3.8、最小函数准则

这是一条在软件工程领域流传久远的规则。严格遵守这条规则会让你的代码可读性更 好,也更容易重构。如果违反这个规则,那么代码会很难被测试或者重用 。

3.9、不要写全局方法 在 JavaScript 中,永远不要污染全局,会在生产环境中产生难以预料的 bug。 举个 例子,比如你在 Array.prototype 上新增一个 diff 方法来判断两个数组的不 同。而你同事也打算做类似的事情,不过他的 diff 方法是用来判断两个数组首位 元素的不同。很明显你们方法会产生冲突,遇到这类问题我们可以用 ES2015/ES6 的 语法来对 Array 进行扩展。

推荐:

class SuperArray extends Array { 
  diff(comparisonArray) { 
    const hash = new Set(comparisonArray); 
    return this.filter(elem => !hash.has(elem)); 
  } 
} 
1
2
3
4
5
6

不推荐:

Array.prototype.diff = function diff(comparisonArray) { 
  const hash = new Set(comparisonArray); 
  return this.filter(elem => !hash.has(elem));
};
1
2
3
4

3.10、推荐函数式编程 函数式变编程可以让代码的逻辑更清晰更优雅,方便测试。 推荐:

const programmerOutput = [ 
  { name: 'Uncle Bobby', linesOfCode: 500 },
  { name: 'Suzie Q', linesOfCode: 1500 }, 
  { name: 'Jimmy Gosling', linesOfCode: 150 }, 
  { name: 'Gracie Hopper', linesOfCode: 1000 } ]; 
let totalOutput=programmerOutput.map(output=> output.linesOfCode) .reduce((totalLines, lines) => totalLines + lines, 0) 

1
2
3
4
5
6
7

不推荐:

const programmerOutput = [
  { name: 'Uncle Bobby', linesOfCode: 500 }, 
  { name: 'Suzie Q', linesOfCode: 1500 }, 
  { name: 'Jimmy Gosling', linesOfCode: 150 }, 
  { name: 'Gracie Hopper', linesOfCode: 1000 }]; 
let totalOutput = 0; 
for (let i = 0; i < programmerOutput.length; i++) { 
  totalOutput += programmerOutput[i].linesOfCode;
}
1
2
3
4
5
6
7
8
9

3.11、使用多态替换条件语句 为了让代码更简洁易读,如果你的函数中出现了条件判断,那么说明你的函数不止干 了一件事情,违反了函数单一原则 ;并且绝大数场景可以使用多态替代

推荐:

class Airplane { // ... } 
  // 波音777 
class Boeing777 extends Airplane { 
  // ... 
  getCruisingAltitude(){
    return this.getMaxAltitude() - this.getPassengerCount(); 
  } 
} 
 
// 空军一号 
class AirForceOne extends Airplane { 
  // ... 
  getCruisingAltitude() { return this.getMaxAltitude(); }
} 
 
// 赛纳斯飞机 
class Cessna extends Airplane { 
  // ... 
  getCruisingAltitude() { 
    return this.getMaxAltitude() - this.getFuelExpenditure(); 
  }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

不推荐:

class Airplane { 
  // ... 
  // 获取巡航高度 
  getCruisingAltitude() { 
    switch (this.type) { 
      case '777': 
      return this.getMaxAltitude() - this.getPassengerCount();
       
      case 'Air Force One':
       
      return this.getMaxAltitude(); 
       
      case 'Cessna': 
       
      return this.getMaxAltitude() - this.getFuelExpenditure(); 
    } 
  }
} 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

3.12、定时器是否清除 代码中使用了定时器 setTimeout 和 setInterval,需要在不使用时进行清除。

mounted () {
 this.timer = setInterval(() => {
   ...
 }, 1000)
},
destroyed () {
 if (this.timer) {
   clearInterval(this.timer)
 }
}
1
2
3
4
5
6
7
8
9
10

3.13、window/body上的监听事件–需要解绑

mounted() {
  window.addEventListener('resize', this.fun)
}
beforeDestroy () {
  window.removeEventListener('resize', this.fun);
}
1
2
3
4
5
6

3.14、可选链访问数组/对象元素

推荐:

cosnt obj = {}
cosnt b = obj?.a?.b
console.log(b)    // undefined
1
2
3

不推荐:

cosnt obj = {}
cosnt b = obj.a && obj.a.b
console.log(b)    // undefined
1
2
3

3.15、判断条件过多需要提取出成方法或者computed 推荐:

<template>
  <t-table v-if="isChangeAvailiable"/>
</template>
<script>
 computed: {
    isChangeAvailiable() {
      return (
        this.satus==1&&this.orderStatus==2&&this.isShowTable
      );
    },
  },
</script>
1
2
3
4
5
6
7
8
9
10
11
12

不推荐:

<template>
  <t-table v-if="satus==1&&orderStatus==2&&isShowTable"/>
</template>
1
2
3

3.16、判断非空(使用空值合并操作符——??)

推荐:

if((value??'') !==''){...}
1

不推荐:

if(value !==null && value !==undefined && value !==''){....}
1

3.17、POST/PUT/DELETE 请求按钮需要添加 loading 状态,防止重复提交。

建议使用UI 框架提供的button 组件的loading属性,或者自己封装一个 loading 状态的按钮组件。

编辑 (opens new window)
上次更新: 2024/03/25, 10:07:50
css实现无缝切换跑马灯样式
懒加载+无感删除list思路

← css实现无缝切换跑马灯样式 懒加载+无感删除list思路→

最近更新
01
懒加载+无感删除list思路
11-12
02
移动端兼容问题
11-12
03
css实现无缝切换跑马灯样式
03-05
更多文章>
Theme by Vdoing | Copyright © 2019-2024 LuNan Ma | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式