规范代码

100 阅读4分钟

规范前端工程代码

代码格式化

  • 安装

    npm install --save-dev --save-exact prettier

  • 新建配置文件,让vscode知道你正在使用Prettier

    echo {}> .prettierrc.json

  • vscode安装prettier-Code formatter插件,并配置vscode保存时自动格式化

html规范

  • 标签必须合法且闭合、嵌套正确,标签名需小写

  • 标签语法无错误,需要符合语义化

  • 空元素标签无需闭合(area、base、br、col、command、embed、hr、img、input、keygen、link、meta、param、source、track、wbr),例如:

        <input type="text">
        <img src="" alt="" srcset="">
    
  • 标签的自定义属性以data-开头,如:<a href="#" data-num='18'></a>

  • <a> 标签加上title属性,<a>标签的href属性必须写上链接地址,暂无的加上javascript:alert('敬请期待!');非本专题的页面间跳转,采用打开新窗口模式:target="_blank"

  • https协议自适应,写法上一律去掉协议http:部分

        <style>
        /* CSS背景图片  */
        .bg{backgroundurl(//game.gtimg.cn/images/hd.jpg);}
        </style>
        <!-- 链接URL -->
        <a href="//cf.qq.com/main.shtml">进入官网</a>
        <!-- 图片SRC -->
        <img src="//game.gtimg.cn/images/cf/web201610/logo.png">
        <!-- JS链接 -->
        <script src="//ossweb-img.qq.com/js/title.js"></script>
    

命名

文件命名

  • 除index.vue之外,其他.vue文件统一用PascalBase风格

    // 创建文件夹/文件
    components/Chat  // 关于聊天的文件夹
    components/Chat/index.vue  //聊天入口文件
    components/Chat/MessageList.vue //聊天记录展示组件
    
    // 组件使用
    import MessageList from './MessageList.vue';
    <message-list></message-list>
    
  • js,scss文件命名全部小写

样式命名

  • 属性的定义,统一使用双引号
  • 类名命名需要语义化
  • class都需小写,名称间隔使用-符号 class="side-nav"
  • id 使用驼峰命名法 id="myCanvas"
  • 禁止通过id选择器定义样式,以免开发过程中id名变化,引起页局错乱

函数/变量命名

  • 命名需要语义化 使用驼峰命名法 const setBeautyStyle = () => {}
  • 私有属性、变量和方法已下划线_开头 var _privateMethod = {};
  • 常量,使用全部字母大写,单词间下划线分隔的命名_, var USR_ID = {};
  • 定义常量使用const,变量使用let,禁止使用var
  • 命名不能以_,$以及其他特殊符号结尾

接口相关函数命名

add(增) / update(改) / delete(删) / get(查)

  • 例如获取所有案件列表 getCaseList,新增案件 addCase,修改案件信息updateCaseInfo,删除案件 deleteCase,获取案件详情 getCaseDeatil

图片命名

  • 图片名称必须小写,禁止使用特殊字符、中文

  • 使用英文或拼音缩写,禁止特殊字符

  • 名称间隔使用-符号

  • 命名需要能体现图片的大概用途

    bg.jpg          //背景图片
    mod-bg.jpg      //模块背景
    sprites.png     //精灵图
    btn-start.png   //开始按钮
    ico-play.png    //修饰性图片
    

字符串

  • 定义字符串均使用es6的写法

    const innerHtml = `我的名字叫做${name}`
    

css规范

  • 命名见上

  • 鉴于使用的UI框架为element-plus,所以样式均采用sass预编译器处理。

  • 书写规范选择属性嵌套规则

    .content-container {
        width: 100%;
        height: 100%;
        display: flex;
        .voice-page-box {
            position: fixed;
            padding: 20px;
            width: 100%;
            p {
                color: #fff;
                margin: 0;
            }
        }
    
  • 定义变量,命名均是小写字母和-连接,便于维护

    • 初始化底层公共base.scss,可在此文件内定义主题色相关变量,字体变量等等。

          /*统一定义默认字体*/ 
          $base-font-family:"PingFang SC", "Microsoft YaHei",Arial,Helvetica,sans-serif,"SimSun",monospace ; 
          /*统一默认字体颜色*/
          $u-content-color: #606266;
          /*统一定义主题色*/
          $u-type-primary: #0246BE;
          $u-type-success: #11b760;
          $u-type-error: #fa3534;
          $u-type-warning:  #ff6200;
          $u-type-info: #909399;
          :root {
              --el-color-primary: $u-type-primary;
              --el-color-success:$u-type-success;
              --el-color-error:$u-type-error;
              --el-color-warning:$u-type-warning;
              --el-color-info:$u-type-info;
          }
          /*统一定义头部的高度*/
          $headerHeight:64px;
          /*统一定义盒子的圆角*/
          $border-radius-small: 6px; 
          $border-radius-large: 12px;
      
    • 变量使用方法

          /*取消默认样式*/ 
          p,h1,h2,h3,h4,h5,h6,ul,li,ol,input,i,span,div,html,body{
              margin: 0;
              padding: 0;
              font-style: normal;
              outline-style: none;
              color: $u-main-color;
              font-family:$base-font-family;
              box-sizing: border-box;
          }
      
  • 禁止使用通配符 *

  • 运算符之间空出一个空格

        height: calc(100vh - 30px);
    

注释

  1. html

        ...
        <!-- 活动板块 开始 -->
        <div class="part-act">
        ...
        </div>
        <!-- 活动板块 结束 -->
        ...
    
  2. js

    请注明函数的调用方式,包括函数的用途、参数类型等。

    /**
    * 7.1 设置美颜、美白、红润效果级别
    *
    * SDK 内部集成了两套风格不同的磨皮算法,一套我们取名叫“光滑”,适用于美女秀场,效果比较明显。
    * 另一套我们取名“自然”,磨皮算法更多地保留了面部细节,主观感受上会更加自然。
    *
    * $param {TRTCBeautyStyle} style - 美颜风格,光滑或者自然,光滑风格磨皮更加明显,适合娱乐场景。
    * - TRTCBeautyStyleSmooth: 光滑,适用于美女秀场,效果比较明显。
    * - TRTCBeautyStyleNature: 自然,磨皮算法更多地保留了面部细节,主观感受上会更加自然。
    * $param {Number} beauty    - 美颜级别,取值范围0 - 9,0表示关闭,1 - 9值越大,效果越明显
    * $param {Number} white     - 美白级别,取值范围0 - 9,0表示关闭,1 - 9值越大,效果越明显
    * $param {Number} ruddiness - 红润级别,取值范围0 - 9,0表示关闭,1 - 9值越大,效果越明显,该参数 windows 平台暂未生效
    */
     async setBeautyStyle(style: TRTCBeautyStyle, beauty: number, white: number, ruddiness: number) {
         try {
         if (!this.beautyPlugin) {
             this.beautyPlugin = new RTCBeautyPlugin();
             if (this.localStream) {
             const videoTrack = this.localStream.getVideoTrack();
             if (videoTrack) {
                 this.beautyPlugin.generateBeautyStream(this.localStream);
             }
             }
         }
         const factor = 0.11// electron 美颜范围 1~9, WebRTC 美颜插件取值范围 0.1~1
         const params = {
             beauty: beauty * factor || this.beautyDefaultBeauty,
             brightness: white * factor || this.beautyDefaultBrightness,
             ruddy: ruddiness * factor || this.beautyDefaultRuddy,
         };
         this.beautyPlugin.setBeautyParam(params);
         } catch (error) {
         this.callFunctionErrorManage(error, 'setBeautyStyle');
         }
     }
    
  3. scss

    • 注释规范
        @charset "UTF-8";
    
        /**
        * @desc File Info
        * @author liqinuo
        * @date 2015-10-10
        */
    
        /* Module A
        ----------------------------------------------------------------*/
        .mod_a {}
    
        /* module A logo */
        .mod_a_logo {}
    
        /* module A nav */
        .mod_a_nav {}
    
        /* Module B
        ----------------------------------------------------------------*/
        .mod_b {}
    
        /* module B logo */
        .mod_b_logo {}
    
        /* module B nav */
        .mod_b_nav {}
    

CSS重置样式(可参考)

移动端
/* * { -webkit-tap-highlight-color: transparent; outline: 0; margin: 0; padding: 0; vertical-align: baseline; } */
bodyh1h2h3h4h5h6, hr, pblockquotedldtddulolli, pre, formfieldsetlegendbuttoninputtextareathtd { margin0padding0vertical-align: baseline; }
img { border0 none; vertical-align: top; }
iem { font-style: normal; }
olul { list-style: none; }
input, select, buttonh1h2h3h4h5h6 { font-size100%font-family: inherit; }
table { border-collapse: collapse; border-spacing0; }
a { text-decoration: none; color#666; }
body { margin0 auto; min-width320pxmax-width640pxheight100%font-size14pxfont-family: -apple-system,Helvetica,sans-serif; line-height1.5color#666; -webkit-text-size-adjust: 100% !important; text-size-adjust: 100% !important; }
input[type="text"]textarea { -webkit-appearance: none; -moz-appearance: none; appearance: none; }
PC端
htmlbodydivh1h2h3h4h5h6pdldtddolullifieldsetformlabelinputlegendtablecaptiontbodytfoottheadtrthtdtextareaarticleasideaudiocanvasfigurefooterheadermarkmenunavsectiontimevideo { margin0padding0; }
h1h2h3h4h5h6 { font-size100%font-weight: normal }
articleaside, dialog, figurefooterheaderhgroupnavsectionblockquote { display: block; }
ulol { list-style: none; }
img { border0 none; vertical-align: top; }
blockquoteq { quotes: none; }
blockquote:beforeblockquote:afterq:beforeq:after { content: none; }
table { border-collapse: collapse; border-spacing0; }
strongemi { font-style: normal; font-weight: normal; }
ins { text-decoration: underline; }
del { text-decoration: line-through; }
mark { background: none; }
input::-ms-clear { display: none !important; }
a { text-decoration: none; color#333; }
a:hover { text-decoration: underline; }

本文使用 markdown.com.cn 排版