前端规范 - kylin-qin/Blog GitHub Wiki

尽量采用两空格缩进,而不是Tab, 这样可以避免不同编辑器出现排版不一致问题。

HTML

  • DOM树的设计一定要合理,先垂直方向,再水平方向。
  • 模块间留空行加注释
<!-- header start --->
<div>
  <div></div>
  <div></div>
</div>
<!-- header end --->

<!-- body start --->
<div>
  <div></div>
  <div></div>
</div>
<!-- body end --->

<!-- footer start --->
<div>
  <div></div>
  <div></div>
</div>
<!-- footer end --->
  • 减少不必要的DOM嵌套

CSS

  • 提取全局样式,使用常见名称命名(不要使用某个页面的具体含义命名)例如:header,container,footer,sidebar...
  • 命名采用全小写,用“-”连接。
  • 只属于某个模块的样式命名应采用特定结构,可以减少样式命名冲突,例如:
<!-- 评论 -->
<div class="comment">
  <div class="comment-title"></div>
  <div class="comment-cont"></div>
  <div class="comment-user">
    <div class="comment-user-face"></div>
    <div class="comment-user-name"></div>
  </div>
</div>
  • CSS书写顺序
.header {
  /* 显示属性 */
    display || visibility
    list-style
    position top || right || bottom || left
    z-index
    clear
    float
  /* 自身属性 */
    width max-width || min-width
    height max-height || min-height
    overflow || clip
    margin
    padding
    outline
    border
    background
  /* 文本属性 */
    color
    font
    text-overflow
    text-align
    text-indent
    line-height
    white-space
    vertical-align
    cursor
    content
  };
  • 避免使用低效的选择器
  body > * {…};
  ul > li > a {…};
  #footer > h3 {…};
  ul#top_blue_nav {…};
  searbar span.submit a { … };

JS - ES6时代

  • 开启 Eslint
  • 模块化 - 重复代码提取成函数
  • 使用空格代替tab
  • 杜绝var - 使用const或let来声明所有局部变量。如果变量不需要被重新赋值,默认应该使用const。
  • 优先使用箭头函数
// bad
[1, 2, 3].map(function (x) {
 const y = x + 1;
 return x * y;
});
// good
[1, 2, 3].map((x) => {
 const y = x + 1;
 return x * y;
});
  • 常量的命名规范 - 常量命名应该使用全大写格式,并用下划线分割
  • 每次只声明一个变量
// bad
let a = 1, b = 2, c = 3;
// good
let a = 1;
let b = 2;
let c = 3;
  • 使用单引号
// bad
let directive = "No identification of self or mission."
// bad
let saying = 'Say it ain\u0027t so.';

JS一些其他规范
Airbnb的规范
Airbnb的规范-中文版

⚠️ **GitHub.com Fallback** ⚠️