Front-end Vue code style guide

Table of contents

1. Naming convention

1.1 Naming the project file

1.2 Vue component naming

1.3 Code parameter naming

2. Code specification

2.1 Vue

2.2 HTML

2.3 CSS

2.4 JavaScript

3. Annotation specification

3.1 HTML file comments

3.2 CSS file comments

3.3 JavaScript file comments

4. Others


1. Naming convention

Commonly used naming conventions on the market:

  • camelCase(CamelCase - initial letter lowercase)

  • PascalCase(CamelCase - capitalize the first letter)

  • kebab-case(short horizontal line connection type)

  • Snake(underscore connection type)

1.1 Naming the project file

1.1.1 Project name

All in lowercase, separated by dashes . Example: my-project-name.

1.1.2 Directory name

Refer to the project naming rules. When there is a plural structure, plural nomenclature should be adopted . Example: docs, assets, components, directives, mixins, utils, views.

my-project-name/
|- BuildScript    // 流水线部署文件目录
|- docs           // 项目的细化文档目录(可选)
|- nginx          // 部署在容器上前端项目 nginx 代理文件目录
|- node_modules   // 下载的依赖包
|- public         // 静态页面目录
    |- index.html // 项目入口
|- src            // 源码目录
    |- api        // http 请求目录
    |- assets     // 静态资源目录,这里的资源会被wabpack构建
        |- icon   // icon 存放目录
        |- img    // 图片存放目录
        |- js     // 公共 js 文件目录
        |- scss   // 公共样式 scss 存放目录
            |- frame.scss   // 入口文件
            |- global.scss  // 公共样式
            |- reset.scss   // 重置样式
    |- components     // 组件
    |- plugins        // 插件
    |- router         // 路由
    |- routes         // 详细的路由拆分目录(可选)
        |- index.js
    |- store          // 全局状态管理
    |- utils          // 工具存放目录
        |- request.js // 公共请求工具
    |- views          // 页面存放目录
    |- App.vue        // 根组件
    |- main.js        // 入口文件
    |- tests          // 测试用例
    |- .browserslistrc// 浏览器兼容配置文件
    |- .editorconfig  // 编辑器配置文件
    |- .eslintignore  // eslint 忽略规则
    |- .eslintrc.js   // eslint 规则
    |- .gitignore     // git 忽略规则
    |- babel.config.js // babel 规则
    |- Dockerfile // Docker 部署文件
    |- jest.config.js
    |- package-lock.json
    |- package.json // 依赖
    |- README.md // 项目 README
    |- vue.config.js // webpack 配置

1.1.3 Image file name

All are in lowercase, single-word names are preferred, and multiple word names are separated by underscores .

banner_sina.gif
menu_aboutus.gif
menutitle_news.gif
logo_police.gif
logo_national.gif
pic_people.jpg
pic_TV.jpg

1.1.4 HTML file name

All are in lowercase, single-word names are preferred, and multiple word names are separated by underscores .

|- error_report.html
|- success_report.html

1.1.5 CSS filename

All are in lowercase, single word names are preferred, and multiple word names are separated by dashes .

|- normalize.less
|- base.less
|- date-picker.scss
|- input-number.scss

1.1.6 JavaScript file names

All are in lowercase, single word names are preferred, and multiple word names are separated by dashes .

|- index.js
|- plugin.js
|- util.js
|- date-util.js
|- account-model.js
|- collapse-transition.js

The above rules can be quickly memorized as "underline in static files, dash in compiled files".

1.2 Vue component naming

1.2.1 Single file component name

The file extension is  .vue (  single-file components Single-File Component). Single-file component names should always begin with a word capitalized  (PascalCase).

components/
|- MyComponent.vue

1.2.2 Singleton component name

Components that only have a single active instance should be named with  The a prefix to indicate their uniqueness.

This does not mean that the component can only be used on a single page, but that it is used only once per page. These components never accept any props because they are custom for your application. If you find it necessary to add props, it means that this is actually a reusable component that _just currently_ is only used once per page.

For example, the header and sidebar components are used on almost every page, do not accept props, and are custom-made for this application.

components/
|- TheHeading.vue
|- TheSidebar.vue

1.2.3 Basic component name

Basic components: Basic components that do not include business, independent, and specific functions, such as date pickers , modal boxes , etc. This type of component will be widely used as the basic control of the project, so the API of the component is highly abstracted, and different functions can be realized through different configurations.

Basic components that apply specific styles and conventions (that is, components that display classes, have no logic or state, and do not mix business logic) should all start with a specific prefix - Base. Basic components can be used multiple times in one page, and can also be reused in different pages. They are highly reusable components.

components/
|- BaseButton.vue
|- BaseTable.vue
|- BaseIcon.vue

1.2.4 Business Components

Business component: Unlike the basic component, which only contains a certain function, it is reused by multiple pages in the business (with reusability). The difference between it and the basic component is that the business component will only be used in the current project Used, it is not universal, and will include some services, such as data requests; while the basic component does not contain services, can be used in any project, and has a single function, such as an input box with data verification function.

Components mixed with complex business (with their own   related processing), that is, business components, datashouldprop be  Custom named with a prefix. Business components are in a page. For example: there is a card list in a certain page, and the cards whose style and logic are closely related to the business are business components.

components/
|- CustomCard.vue

1.2.5 Tightly coupled component names

Subcomponents that are tightly coupled to a parent component should be named with the parent component name as a prefix.  Since editors usually organize files alphabetically, doing this keeps related files together.

components/
|- TodoList.vue
|- TodoListItem.vue
|- TodoListItemButton.vue

1.2.6 Order of words in component names

Component names should begin with a high-level (usually descriptive) word and end with a descriptive modifier.  Because editors typically organize files alphabetically, important relationships between components are now clear at a glance. The following components are mainly used for search and setting functions.

components/
|- SearchButtonClear.vue
|- SearchButtonRun.vue
|- SearchInputQuery.vue
|- SearchInputExcludeGlob.vue
|- SettingsCheckboxTerms.vue
|- SettingsCheckboxLaunchOnStartup.vue

There is another way of multi-level directories, put all the search components into the "search" directory, and put all the settings components into the "settings" directory. We only recommend doing this for very large (eg 100+ components) applications, because navigating through multiple levels of directories takes more effort than scrolling through a single components directory.

1.2.7 Full-word component names

Component names should be favored rather than abbreviated.  Autocompletion in editors already makes writing long names cheap, and the clarity it brings is invaluable. Abbreviations that are not commonly used in particular should be avoided.

components/
|- StudentDashboardSettings.vue
|- UserProfileOptions.vue

1.3 Code parameter naming

1.3.1 name

Component names should always be multiple words and should always be PascalCase.  Except for the root component App and  <transition>Vue <component> built-in components such as . Doing this avoids conflicts with existing and future HTML elements, since all HTML element names are single-word.

export default {
  name: 'ToDoList',
  // ...
}

1.3.2 prop

Props should always be named in camelCase when declaring props, and kebab-case in templates and JSX . We simply follow the conventions of each language, which is more naturally camelCase in JavaScript. In HTML it is kebab-case.

<WelcomeMessage greeting-text="hi"/>
export default {
  name: 'MyComponent',
  // ...
  props: {
    greetingText: {
      type: String,
      required: true,
      validator: function (value) {
        return ['syncing', 'synced',].indexOf(value) !== -1
      }
    }
  }
}

1.3.3 router

Vue Router Path is named in kebab-case format.  Words using Snake (such as: /user_info) or camelCase (such as: /userInfo) will be treated as one word, and search engines cannot distinguish semantics.

// bad
{
  path: '/user_info', // user_info 当成一个单词
  name: 'UserInfo',
  component: UserInfo,
  meta: {
    title: ' - 用户',
    desc: ''
  }
},

// good
{
  path: '/user-info', // 能解析成 user info
  name: 'UserInfo',
  component: UserInfo,
  meta: {
    title: ' - 用户',
    desc: ''
  }
},

1.3.4 Components in the template

For most projects, component names should always be PascalCase in single-file components and string templates, but kebab-case in DOM templates.

<!-- 在单文件组件和字符串模板中 --> 
<MyComponent/>

<!-- 在 DOM 模板中 --> 
<my-component></my-component>

1.3.5 Self-closing components

Components without content should be self-closing in single-file components, string templates, and JSX -- but never in DOM templates.

<!-- 在单文件组件和字符串模板中 -->
<MyComponent/>

<!-- 在所有地方 -->
<my-component></my-component>

1.3.6 Variables

  • Naming method: camelCase

  • Naming convention: type + object description or attribute

// bad
var getTitle = "LoginTable"

// good
let tableTitle = "LoginTable"
let mySchool = "我的学校"

1.3.7 Constants

  • Naming method: all uppercase underscores

  • Naming convention: Use uppercase letters and underscores to combine names, and underscores to separate words

const MAX_COUNT = 10
const URL = 'http://test.host.com'

1.3.8 Methods

  • Naming method: camelCase

  • Naming convention: uniform use of verbs or verbs + nouns

// 1、普通情况下,使用动词 + 名词形式
// bad
go、nextPage、show、open、login

// good
jumpPage、openCarInfoDialog

// 2、请求数据方法,以 data 结尾
// bad
takeData、confirmData、getList、postForm

// good
getListData、postFormData

// 3、单个动词的情况
init、refresh
verb meaning return value
can Judging whether an action can be performed (right) The function returns a boolean value. true: executable; false: not executable;
has Determine if it contains a value The function returns a boolean value. true: contains this value; false: does not contain this value;
is Determine whether it is a certain value The function returns a boolean value. true: a certain value; false: not a certain value;
get get a value function returns a non-boolean value
set set a value No return value, return whether the setting is successful or return a chained object

1.3.9 Custom Events

Custom events should always use kebab-case event names.

Unlike components and props, there is no automatic case conversion of event names. Instead, the name of the event that is triggered needs to exactly match the name used to listen to this event.

this.$emit('my-event')
<MyComponent @my-event="handleDoSomething" />

Unlike components and props, the event name will not be used as a JavaScript variable name or property name, so there is no reason to use camelCase or PascalCase. And  v-on the event listener will be automatically converted to all lowercase in the DOM template (because HTML is case-insensitive), so it  v-on:myEvent will become  v-on:myevent- making it  myEvent impossible to be monitored.

  • Native event reference list[1]

From native events, it can be found that its usage is as follows:

<div
  @blur="toggleHeaderFocus"
  @focus="toggleHeaderFocus"
  @click="toggleMenu"
  @keydown.esc="handleKeydown"
  @keydown.enter="handleKeydown"
  @keydown.up.prevent="handleKeydown"
  @keydown.down.prevent="handleKeydown"
  @keydown.tab="handleKeydown"
  @keydown.delete="handleKeydown"
  @mouseenter="hasMouseHoverHead = true"
  @mouseleave="hasMouseHoverHead = false">
</div>

In order to distinguish between the use of _native events_ and _custom events_ in Vue, it is recommended that in addition to using kebab-case for multi-word event names, the naming must also follow the form of + verbs, as  on follows  :

<!-- 父组件 -->
<div
  @on-search="handleSearch"
  @on-clear="handleClear"
  @on-clickoutside="handleClickOutside">
</div>
// 子组件
export default {
  methods: {
    handleTriggerItem () {
      this.$emit('on-clear')
    }
  }
}

1.3.10 Event method

  • Naming method: camelCase

  • Naming convention: handle + name (optional) + verb

<template>
  <div
    @click.native.stop="handleItemClick()"
    @mouseenter.native.stop="handleItemHover()">
  </div>
</template>

<script>

export default {
  methods: {
    handleItemClick () {
      //...
    },
    handleItemHover () {
      //...
    }
  }
}
</script>

2. Code specification

2.1 Vue

2.1.1 Code structure

<template>
  <div id="my-component">
    <DemoComponent />
  </div>
</template>

<script>
import DemoComponent from '../components/DemoComponent'

export default {
  name: 'MyComponent',
  components: {
    DemoComponent
  },
  mixins: [],
  props: {},
  data () {
    return {}
  },
  computed: {},
  watch: {}
  created () {},
  mounted () {},
  destroyed () {},
  methods: {},
}
</script>

<style lang="scss" scoped>
#my-component {
}
</style>

2.1.2 data

Component's  data must be a function.

// In a .vue file
export default {
  data () {
    return {
      foo: 'bar'
    }
  }
}

2.1.3 prop

Prop definitions should be as detailed as possible.

export default {
  props: {
    status: {
      type: String,
      required: true,
      validator: function (value) {
        return [
          'syncing', 
          'synced',
          'version-conflict',
          'error'
        ].indexOf(value) !== -1
      }
    }
  }
}

2.1.4 computed

Complex computed properties should be split into as many simpler properties as possible.  Small, focused computed properties reduce hypothetical constraints on information usage, so less refactoring is required as requirements change.

// bad
computed: { 
  price: function () { 
    var basePrice = this.manufactureCost / (1 - this.profitMargin) 
    return ( 
      basePrice - 
      basePrice * (this.discountPercent || 0) 
    ) 
  } 
}

// good
computed: {
  basePrice: function () {
    return this.manufactureCost / (1 - this.profitMargin)
  },
  discount: function () {
    return this.basePrice * (this.discountPercent || 0)
  },
  finalPrice: function () {
    return this.basePrice - this.discount
  }
}

2.1.5 To  v-for set the key value

Collocation must be used on components  key in v-for order to maintain the state of the internal components and their subtrees. Even maintain predictable behavior on elements, such as object constancy in animations [2].

<ul>
  <li
    v-for="todo in todos"
    :key="todo.id">
      {
   
   { todo.text }}
  </li>
</ul>

2.1.6  v-if and  v-for mutual exclusion

Never use  v-if and  v-for both on the same element.

<!-- bad:控制台报错 -->
<ul>
  <li
    v-for="user in users"
    v-if="shouldShowUsers"
    :key="user.id">
      {
   
   { user.name }}
  </li>
</ul>

Generally we tend to do this in two common situations:

  • In order to filter items in a list (for example  v-for="user in users" v-if="user.isActive"). In this case,  users replace with a computed property (eg  activeUsers) that returns the filtered list.

computed: {
  activeUsers: function () {
    return this.users.filter((user) => {
      return user.isActive
    })
  }
}
<ul>
  <li
    v-for="user in activeUsers"
    :key="user.id">
      {
   
   { user.name }}
  </li>
</ul>
  • To avoid rendering lists that should be hidden (eg  v-for="user in users" v-if="shouldShowUsers". In this case,  v-if move to the container element (eg  ulol).

<!-- bad -->
<ul>
  <li
    v-for="user in users"
    v-if="shouldShowUsers"
    :key="user.id">
      {
   
   { user.name }}
  </li>
</ul>

<!-- good -->
<ul v-if="shouldShowUsers">
  <li
    v-for="user in users"
    :key="user.id">
      {
   
   { user.name }}
  </li>
</ul>

2.1.7 Multiple attribute elements

Elements with multiple attributes should be written in multiple lines, one for each attribute.

<!-- bad -->
<img src="https://vuejs.org/images/logo.png" alt="Vue Logo">
<MyComponent foo="a" bar="b" baz="c"/>
<!-- good -->
<img
  src="https://vuejs.org/images/logo.png"
  alt="Vue Logo">

<MyComponent
  foo="a"
  bar="b"
  baz="c"/>

2.1.8 Simple expressions in templates

Component templates should only contain simple expressions, and complex expressions should be refactored into computed properties or methods.

Complex expressions can make your templates less declarative. We should try to describe what should be there , not how to calculate that value. And computed properties and methods make code reusable.

// bad
{
   
   {
  fullName.split(' ').map((word) => {
    return word[0].toUpperCase() + word.slice(1)
  }).join(' ')
}}

Better practice:

<!-- 在模板中 -->
{
   
   { normalizedFullName }}
// 复杂表达式已经移入一个计算属性
computed: {
  normalizedFullName: function () {
    return this.fullName.split(' ').map(function (word) {
      return word[0].toUpperCase() + word.slice(1)
    }).join(' ')
  }
}

2.1.9 Quoted attribute values

Non-empty HTML attribute values ​​should always be enclosed in double quotes.

<!-- bad -->
<input type=text>
<AppSidebar :style={width:sidebarWidth+'px'}>
<!-- good -->
<input type="text">
<AppSidebar :style="{ width: sidebarWidth + 'px' }">

2.1.10 Command abbreviation

  • : expressed  by v-bind:

  • @ expressed  by v-on:

  • # expressed  by v-slot:

<input
  :value="newTodoText"
  :placeholder="newTodoInstructions">

<input
  @input="onInput"
  @focus="onFocus">

<template #header>
  <h1>Here might be a page title</h1>
</template>

<template #footer>
  <p>Here's some contact info</p>
</template>

2.2 HTML

2.2.1 File Templates

HTML5 file template:

<!DOCTYPE html>
  <html lang="zh-CN">
  <head>
    <meta charset="UTF-8">
    <title>HTML5标准模版</title>
  </head>
  <body>
  </body>
</html>

Mobile terminal:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
    <meta name="format-detection" content="telephone=no">
    <title>移动端HTML模版</title>

    <!-- S DNS预解析 -->
    <link rel="dns-prefetch" href="">
    <!-- E DNS预解析 -->

    <!-- S 线上样式页面片,开发请直接取消注释引用 -->
    <!-- #include virtual="" -->
    <!-- E 线上样式页面片 -->

    <!-- S 本地调试,根据开发模式选择调试方式,请开发删除 -->
    <link rel="stylesheet" href="css/index.css">
    <!-- /本地调试方式 -->

    <link rel="stylesheet" href="http://srcPath/index.css">
    <!-- /开发机调试方式 -->
    <!-- E 本地调试 -->

</head>
<body>
</body>
</html>

PC side:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="keywords" content="your keywords">
    <meta name="description" content="your description">
    <meta name="author" content="author,email address">
    <meta name="robots" content="index,follow">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <meta name="renderer" content="ie-stand">
    <title>PC端HTML模版</title>

    <!-- S DNS预解析 -->
    <link rel="dns-prefetch" href="">
    <!-- E DNS预解析 -->

    <!-- S 线上样式页面片,开发请直接取消注释引用 -->
    <!-- #include virtual="" -->
    <!-- E 线上样式页面片 -->

    <!-- S 本地调试,根据开发模式选择调试方式,请开发删除 -->
    <link rel="stylesheet" href="css/index.css">
    <!-- /本地调试方式 -->

    <link rel="stylesheet" href="http://srcPath/index.css">
    <!-- /开发机调试方式 -->
    <!-- E 本地调试 -->
</head>
<body>
</body>
</html>

2.2.2 Element and label closure

There are five types of HTML elements:

  • 空元素:area、base、br、col、command、embed、hr、img、input、keygen、link、meta、param、source、track、wbr

  • Raw text elements: script, style

  • RCDATA elements: textarea, title

  • Foreign elements: elements from the MathML namespace and the SVG namespace

  • Regular elements: Other elements allowed by HTML are called regular elements

In order to allow the browser to better parse the code and make the code more readable, there are the following conventions:

  • All elements with start tags and end tags must be written with start and stop tags, and some elements that allow omission of start tags or bundle tags must also be written.

  • Empty element tags do not add "/" characters.

<!-- good -->
<div>
    <h1>我是h1标题</h1>
    <p>我是一段文字,我有始有终,浏览器能正确解析</p>
</div>
 
<br data-tomark-pass>

<!-- bad -->
<div>
    <h1>我是h1标题</h1>
    <p>我是一段文字,我有始无终,浏览器亦能正确解析
</div>

<br/>

2.2.3 Code nesting

Element nesting specification, each block element is on its own line, and inline elements are optional.

<!-- good -->
<div>
    <h1></h1>
    <p></p>
</div> 
<p><span></span><span></span></p>

<!-- bad -->
<div>
    <h1></h1><p></p>
</div> 
<p> 
    <span></span>
    <span></span>
</p>

Paragraph and heading elements can only nest inline elements.

<!-- good -->
<h1><span></span></h1>
<p><span></span><span></span></p>

<!-- bad -->
<h1><div></div></h1>
<p><div></div><div></div></p>

2.3 CSS

2.3.1 Style files

The style file must be written with  @charset rules, and it must start writing at the first character position of the first line of the style file, and the encoding name is used  “UTF-8”.

  • recommend:

@charset "UTF-8";
.jdc {}
  • Not recommended:

/* @charset规则不在文件首行首个字符开始 */
@charset "UTF-8";
.jdc {}

/* @charset规则没有用小写 */
@CHARSET "UTF-8";
.jdc {}

/* 无@charset规则 */
.jdc {}

2.3.2 Code formatting

There are generally two types of style writing: one is the compact format (Compact), and the other is the expanded format (Expanded).

  • Recommendation: Expanded format (Expanded)

.jdc {
  display: block;
  width: 50px;
}
  • Not recommended: compact format (Compact)

.jdc { display: block; width: 50px;}

2.3.3 Code case

Style selectors, attribute names, and attribute value keywords are all written in lowercase letters, and attribute strings are allowed to use uppercase and lowercase letters.

  • recommend:

.jdc {
  display: block;
}
  • Not recommended:

.JDC {
  DISPLAY: BLOCK;
}

2.3.4 Code readability

  1. There is a space between the opening parenthesis and the class name, and a space between the colon and the attribute value.

  • recommend:

.jdc {
  width: 100%;
}
  • Not recommended:

.jdc{
  width:100%;
}
  1. Comma-separated values, with a space after the comma.

  • recommend:

.jdc {
  box-shadow: 1px 1px 1px #333, 2px 2px 2px #ccc;
}
  • Not recommended:

.jdc {
  box-shadow: 1px 1px 1px #333,2px 2px 2px #ccc;
}
  1. Start a new line for a single CSS selector or a new declaration.

  • recommend:

.jdc, .jdc_logo, .jdc_hd {
  color: #ff0;
}

.nav{
  color: #fff;
}
  • Not recommended:

.jdc, .jdc_logo, .jdc_hd {
  color: #ff0;
}.nav{
  color: #fff;
}
  1. There is no need for spaces in the color value  rgb() rgba() hsl() hsla() rect() , and the value should not contain unnecessary 0s.

  • recommend:

.jdc {
  color: rgba(255,255,255,.5);
}
  • Not recommended:

.jdc {
  color: rgba( 255, 255, 255, 0.5 );
}
  1. The property value hexadecimal value can be abbreviated as much as possible.

  • recommend:

.jdc {
  color: #fff;
}
  • Not recommended:

.jdc {
  color: #ffffff;
}
  1. Do not  0 specify units.

  • recommend:

.jdc {
  margin: 0 10px;
}
  • Not recommended:

.jdc {
  margin: 0px 10px;
}

2.3.5 Attribute Value Quotes

When quotation marks are required for CSS attribute values, use single quotation marks uniformly.

  • recommend:

.jdc {
  font-family: 'Hiragino Sans GB';
}
  • Not recommended:

.jdc {
  font-family: "Hiragino Sans GB";
}

2.3.6 Suggestions for writing attributes

The following sequence is recommended:

  1. Layout positioning properties: display / position / float / clear / visibility / overflow

  2. Own attributes: width / height / margin / padding / border / background

  3. Text attributes: color / font / text-decoration / text-align / vertical-align / white-space / break-word

  4. Other properties (CSS3): content / cursor / border-radius / box-shadow / text-shadow / background: linear-gradient …

.jdc {
  display: block;
  position: relative;
  float: left;
  width: 100px;
  height: 100px;
  margin: 0 10px;
  padding: 20px 0;
  font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif;
  color: #333;
  background: rgba(0,0,0,.5);
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  -o-border-radius: 10px;
  -ms-border-radius: 10px;
  border-radius: 10px;
}

3.3.7 CSS3 browser-specific prefixes

CSS3 browser-proprietary prefixes come first, standard prefixes follow.

.jdc {
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  -o-border-radius: 10px;
  -ms-border-radius: 10px;
  border-radius: 10px;
}

2.4 JavaScript

2.4.1 Single-line code blocks

Use spaces in single-line code blocks.

  • Not recommended:

function foo () {return true}
if (foo) {bar = 0}
  • recommend:

function foo () { return true }
if (foo) { bar = 0 }

2.4.2 Brace style

In the programming process, the curly brace style is closely related to the indentation style, and there are many ways to describe the position of the curly brace relative to the code block. In JavaScript, there are three main styles, as follows:

  • 【Recommendation】One True Brace Style

if (foo) {
  bar()
} else {
  baz()
}
  • Stroustrup

if (foo) {
  bar()
}
else {
  baz()
}
  • Allman

if (foo)
{
  bar()
}
else
{
  baz()
}

2.4.3 Spaces in code

  1. Spaces before and after commas can improve the readability of the code. The team agrees to use spaces after commas and not before commas.

  • recommend:

var foo = 1, bar = 2
  • Not recommended:

var foo = 1,bar = 2

var foo = 1 , bar = 2

var foo = 1 ,bar = 2
  1. There can be no space between the key and value of the object literal, and there is a space between the colon and the value of the object literal.

  • recommend:

var obj = { 'foo': 'haha' }
  • Not recommended:

var obj = { 'foo' : 'haha' }
  1. Add spaces before code blocks.

  • recommend:

if (a) {
  b()
}

function a () {}
  • Not recommended:

if (a){
  b()
}

function a (){}
  1. Spaces are required before function declaration brackets.

  • recommend:

function func (x) {
  // ...
}
  • Not recommended:

function func(x) {
  // ...
}
  1. Spaces are prohibited in function calls.

  • recommend:

fn()
  • Not recommended:

fn ()

fn
()
  1. Spaces are required before and after the operator.

  • recommend:

var sum = 1 + 2
  • Not recommended:

var sum = 1+2

3. Annotation specification

Purpose of comments:

  • Improve code readability and thus code maintainability

Principles of annotation:

  • Do not add comments if not necessary ( As short as possible )

  • Be as long as necessary ( As long as necessary )

3.1 HTML file comments

3.1.1 Single-line comments

Generally used for simple descriptions, such as certain state descriptions, attribute descriptions, etc.

There is a space character before and after the comment content, and the comment is located above the code to be commented, occupying a single line.

  • recommend:

<!-- Comment Text -->
<div>...</div>
  • Not recommended

<div>...</div><!-- Comment Text -->

<div><!-- Comment Text -->
  ...
</div>

3.1.2 Module Notes

Generally used to describe the name of the module and where the module starts and ends.

A space character before and after the comment content  <!-- S Comment Text \-->indicates the beginning of the module and  <!-- E Comment Text \-->the end of the module, and there is a line between the modules.

  • recommend:

<!-- S Comment Text A --> 
<div class="mod_a">
  ...
</div>
<!-- E Comment Text A -->
 
<!-- S Comment Text B --> 
<div class="mod_b">
  ...
</div>
<!-- E Comment Text B -->
  • Not recommended

<!-- S Comment Text A -->
<div class="mod_a">
  ...
</div>
<!-- E Comment Text A -->
<!-- S Comment Text B --> 
<div class="mod_b">
  ...
</div>
<!-- E Comment Text B -->

3.1.3 Nested module comments

When module comments reappear within module comments, nested modules are no longer used in order to highlight the main module.

<!-- S Comment Text -->
<!-- E Comment Text -->

Instead use

<!-- /Comment Text -->

Comments are written on a separate line at the bottom of the module's closing tag.

<!-- S Comment Text A -->
<div class="mod_a">
  
    <div class="mod_b">
        ...
    </div>
    <!-- /mod_b -->
     
    <div class="mod_c">
     ...
    </div>
    <!-- /mod_c -->
  
</div>
<!-- E Comment Text A -->

3.2 CSS file comments

3.2.1 Single-line comments

The first character and the last character of the comment content are both a space character, occupying a single line, with one line between each line.

  • recommend:

/* Comment Text */ 
.jdc {} 

/* Comment Text */ 
.jdc {}
  • Not recommended:

/*Comment Text*/
.jdc {
  display: block;
}

.jdc {
  display: block;/*Comment Text*/
}

3.2.2 Module Notes

The first character and the last character of the comment content are both a space character, which /* occupies one line with the module information description, and multiple horizontal line separators  - occupy  */ one line, and there are two lines between lines.

  • recommend:

/* Module A
---------------------------------------------------------------- */
.mod_a {}


/* Module B
---------------------------------------------------------------- */
.mod_b {}
  • Not recommended:

/* Module A ---------------------------------------------------- */
.mod_a {}
/* Module B ---------------------------------------------------- */
.mod_b {}

3.2.3 File comments

@charset Indicate the page name, author, creation date and other information below the style file coding declaration  statement.

@charset "UTF-8";
/**
 * @desc File Info
 * @author Author Name
 * @date 2015-10-10
 */

3.3 JavaScript file comments

3.3.1 Single-line comments

Single-line comments are used  //, and comments should be written on a single line above the commented object, not appended to a statement.

  • recommend:

// is current tab
const active = true
  • Not recommended:

const active = true // is current tab

A blank line is required above a comment line ( unless the comment line is at the top of a block ) for readability.

  • recommend:

function getType () {  
  console.log('fetching type...')
  
  // set the default type to 'no type'
  const type = this.type || 'no type'
  return type
}
// 注释行上面是一个块的顶部时不需要空行
function getType () {  
  // set the default type to 'no type'
  const type = this.type || 'no type'   
  return type
}
  • Not recommended:

function getType () {  
  console.log('fetching type...')
  // set the default type to 'no type'
  const type = this.type || 'no type'
  return type
}

3.3.2 Multi-line comments

Use multiline comments  /** ... */instead of multiline  //.

  • recommend:

/**
 * make() returns a new element
 * based on the passed-in tag name
 */
function make (tag) {
  // ...

  return element
}
  • Not recommended:

// make() returns a new element
// based on the passed in tag name
function make (tag) {
  // ...

  return element
}

3.3.3 Comment spaces

There needs to be a space between the comment content and the comment character to improve readability. eslint:  spaced-comment.

  • recommend:

// is current tab
const active = true

/**
 * make() returns a new element
 * based on the passed-in tag name
 */
function make(tag) {  
  // ...

  return element
}
  • Not recommended:

//is current tab
const active = true

/**
 *make() returns a new element
 *based on the passed-in tag name
 */
function make(tag) {  
  // ...

  return element
}

3.3.4 Special marking

Sometimes we find a possible bug, but we can't fix it for some reason; or there are still some functions to be completed somewhere, at this time we need to use the corresponding special mark annotation to inform future self or collaborators. There are two commonly used special tags:

  • // FIXME : Explain what the problem is

    • // TODO : Explain what to do or the solution to the problem

class Calculator extends Abacus {
  constructor () {
    super ()

      // FIXME: shouldn’t use a global here
      total = 0

      // TODO: total should be configurable by an options param
      this.total = 0
  }
}

3.3.5 Document class comments

Documentation class annotations, such as functions, classes, files, events, etc.; all use the jsdoc specification.

/**
 * Book类,代表一个书本.
 * @constructor
 * @param {string} title - 书本的标题.
 * @param {string} author - 书本的作者.
 */
function Book (title, author) {
  this.title = title
  this.author = author
}

Book.prototype = {
  /**
   * 获取书本的标题
   * @returns {string|*}
   */
  getTitle: function () {
    return this.title
  },
  /**
   * 设置书本的页数
   * @param pageNum {number} 页数
   */
  setPageNum: function (pageNum) {
    this.pageNum=pageNum
  }
}

3.3.6 Annotation tools

ESLint It is the most popular JS code inspection tool at the moment. ESLint There are some annotation-related rules in it, which users can choose to open:

  • valid-jsdoc

  • require-jsdoc

  • no-warning-comments

  • capitalized-comments

  • line-comment-position

  • lines-around-comment

  • multiline-comment-style

  • no-inline-comments

  • spaced-comment

4. Others

  • Use two spaces for indentation and line breaks.

  • It is recommended to add a semicolon at the end of the JavaScript code for large-scale multi-person collaboration projects.

  • For small personal innovation and practice projects, you can try to use the style without semicolons at the end of the JavaScript code, which is more refreshing and concise.

Guess you like

Origin blog.csdn.net/qq_44848480/article/details/129275044