7

One, naming convention

Common naming conventions on the market:

camelCase (little camel case nomenclature-lower case initials)
PascalCase (big camel case nomenclature-first letter capitalized)
kebab-case (short horizontal line connection type)
Snake (underlined connection type)

1.1 Name the project file

1.1.1 Project name

All lower case, separated by dashes. Example: my-project-name.

1.1.2 Directory name

refers to the project naming rules. If there is a plural structure, use the plural nomenclature . Examples: 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 lower case, and single word names are preferred, and multiple words are named 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 lower case, and single word names are preferred, and multiple words are named separated by underscores.

|- error_report.html
|- success_report.html

1.1.5 CSS file name

All are in lower case. Single word names are preferred, and multiple words are named by dashes.

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

1.1.6 JavaScript file name

All are in lower case. Single word names are preferred, and multiple words are named by dashes.

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

1.2 Vue component naming

1.2.1 Single file component name

Single-file components with the file extension .vue. Single-file component names should always start with a capital letter (PascalCase).

components/
|- MyComponent.vue

1.2.2 Singleton component name

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

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

For example, the header and sidebar components are used on almost every page, and props are not accepted. This component is specifically customized for the application.

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

1.2.3 Basic component name

Basic components: basic components that do not include business, are independent, and have specific functions, such as date pickers, modal boxes, etc. As the basic control of the project, this kind of components will be used in large quantities. Therefore, the API of the component is too high-strength abstraction, and different functions can be realized through different configurations.

The basic components that apply specific styles and conventions (that is, display-like, non-logic or stateless, and non-doped business logic components) should all start with a specific prefix-Base. basic component can be used multiple times in one page, and can also be reused in different pages. It is a highly reusable component.

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

1.2.4 Business Components

Business component: It is not like the basic component that only contains a certain function, but 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 contain some services, such as data requests; and the basic components do not contain services and can be used in any project, with a single function, such as an input box with a data verification function.

Components with complex services (with their own data and prop related processing), that is, business components, should be named with the prefix Custom. Business components are in a page. For example, there is a list of cards in a 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

Child components that are tightly coupled to the parent component should be named with the parent component name as a prefix. Because editors usually organize files in alphabetical order, this can arrange related files together.

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

1.2.6 The order of words in component names

Component names should start with high-level (usually general description) words and end with descriptive modifiers. Because editors usually organize files in alphabetical order, the 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 multi-level directory method, put all the search components in the "search" directory, and put all the setting components in the "settings" directory. We only recommend considering this for very large applications (such as 100+ components), because it takes more effort to search through multi-level directories than to scroll through a single components directory.

1.2.7 Complete word component name

component name should be inclined rather than the abbreviation . The auto-completion in the editor has made the cost of writing long names very low, but the clarity it brings is very valuable. In particular, abbreviations that are not commonly used should be avoided.

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

1.3 Code parameter naming

1.3.1 name

component name of 161bc357a14196 should always be multiple words, and it should always be of PascalCase. Except for the root component App and Vue built-in components such as <transition> and <component>. Doing so can avoid conflicts with existing and future HTML elements, because all HTML element names are single words.

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

1.3.2 prop

When declaring prop, its naming should always use camelCase, and kebab-case should always be used in templates and JSX. We simply follow the conventions of each language, and camelCase is more natural 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. A word using Snake (such as: /user_info) or camelCase (such as: /userInfo) will be treated as a 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, the component name should always be PascalCase in single-file components and string templates, but it should always be kebab-case in DOM templates.

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

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

1.3.5 Self-closing components

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

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

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

1.3.6 Variables

Naming method: camelCase
Naming convention: type + object description or attribute method

// bad
var getTitle = "LoginTable"

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

1.3.7 Constants

Naming method: all uppercase and underlined division
Naming conventions: use capital letters and underscores to combine names, and underscores are used to separate words

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

1.3.8 Method

Naming method: camelCase
Naming convention: uniform use of verb or verb + noun form

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

// good
jumpPage、openCarInfoDialog

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

// good
getListData、postFormData

// 3、单个动词的情况
init、refresh
verbmeaningreturn value
canDetermine whether a certain action (right) can be performedThe function returns a Boolean value. true: executable; false: not executable;
hasDetermine whether it contains a certain valueThe function returns a Boolean value. true: contains this value; false: does not contain this value;
isDetermine whether it is a certain valueThe function returns a Boolean value. true: a certain value; false: not a certain value;
getGet a valueFunction returns a non-boolean value
setSet a certain valueNo return value, return whether the setting is successful or return a chained object

1.3.9 Custom Event

Custom events should always use the event name of kebab-case.

Unlike components and props, there is no automatic case conversion for event names. Instead, the name of the triggered event needs to exactly match the name used to monitor 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 the v-on event listener will be automatically converted to all lowercase in the DOM template (because HTML is case-insensitive), so v-on:myEvent will become v-on:myevent-making myEvent impossible Was overheard.

Native event reference list

From the original event, 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 the use of _native events_ and _custom events_ in Vue, it is recommended that in addition to the use of kebab-case for multi-word event names, the naming should also be in the form of on + verb, as 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

The data of the component 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

should split the complex calculation attributes into as many simpler attributes as possible, . The small, focused calculation attributes reduce the hypothetical restrictions on the use of information, so there is no need to refactor so much when the 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 Set the key value for v-for

You must use key with v-for on components to maintain the state of internal components and their subtrees.

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

2.1.6 v-if and v-for are mutually exclusive

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

<!-- 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:

To filter the items in a list (such as v-for="user in users" v-if="user.isActive"). In this case, replace users with a calculated attribute (such as activeUsers) and let it return 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 (such as v-for="user in users" v-if="shouldShowUsers"). In this case, please move the v-if to the container element (such as ul, ol).

<!-- 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 of multiple attributes should be written in multiple lines, one line 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 calculated properties or methods.

Complex expressions can make your templates less declarative. We should try to describe what should appear, not how to calculate that value. And computing properties and methods make the 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 abbreviations

Use: to indicate v-bind:
Use @ to denote v-on:
Use # to indicate 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 template

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 5 types of HTML elements:

Empty elements: area, base, br, col, command, embed, hr, img, input, keygen, link, meta, param, source, track, wbr

Original 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 make the browser 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 end tags, and some elements that allow the omission of start tags or bundle tags must also be written.
No "/" character is added to the empty element tags.

<!-- 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 elements 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 file
The style file must be written with the @charset rule, and must be written at the first character position of the first line of the style file, and the code name is "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

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

2.3.3 Code case

The style selector, attribute name, and attribute value keywords are all written in lowercase letters, and uppercase and lowercase are allowed for attribute strings.

recommend:

.jdc {
  display: block;
}

Not recommended:

.JDC {
  DISPLAY: BLOCK;
}

2.3.4 Code legibility

1. A space between the left bracket and the class name, and a space between the colon and the attribute value.

recommend:

.jdc {
  width: 100%;
}

Not recommended:

.jdc{
  width:100%;
}

2. Values separated by commas, 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;
}

3. Open a new line for a single CSS selector or 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;
}

4. The color value rgb() rgba() hsl() hsla() rect() does not need spaces, 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 );
}

5. The hexadecimal value of the attribute value can be abbreviated as much as possible.

recommend:

.jdc {
  color: #fff;
}

Not recommended:

.jdc {
  color: #ffffff;
}

6. Do not specify the unit for 0.

recommend:

.jdc {
  margin: 0 10px;
}

Not recommended:

.jdc {
  margin: 0px 10px;
}

2.3.5 Property value quotes

When CSS property values need to use quotation marks, 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 order is recommended:

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

Own properties: width / height / margin / padding / border / background

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

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 private prefix

The CSS3 browser private prefix comes first, and the standard prefix comes last.

.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 One-line code block

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 Bracket style

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

[Recommended] 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 the code

1. The space before and after the comma can improve the readability of the code. The team agreed to use a space after the comma, and no space before the comma.

recommend:

var foo = 1, bar = 2

Not recommended:

var foo = 1,bar = 2

var foo = 1 , bar = 2

var foo = 1 ,bar = 2

2. There can be no space between the key and value of the object literal, and there must be a space between the colon and the value of the object literal.

recommend:

var obj = { 'foo': 'haha' }

Not recommended:

var obj = { 'foo' : 'haha' }

3. Add a space before the code block.

recommend:

if (a) {
  b()
}

function a () {}

Not recommended:

if (a){
  b()
}

function a (){}

4. Add a space before the parentheses of the function declaration.

recommend:

function func (x) {
  // ...
}

Not recommended:

function func(x) {
  // ...
}

5. Spaces are forbidden when calling functions.

recommend:

fn()

Not recommended:

fn ()

fn
()

6. Spaces need to be added before and after the operator.

recommend:

var sum = 1 + 2

Not recommended:

var sum = 1+2

Three, annotation specification

Purpose of annotation:

Improve the readability of the code, thereby improving the maintainability of the code
The principle of annotation:

If not necessary, do not add comments (As short as possible)

If necessary, try to be as detailed as possible (As long as necessary)

3.1 HTML file comment

3.1.1 Single-line comments

Generally used for simple descriptions, such as some 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 on a separate line.

recommend:

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

Not recommended:

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

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

3.1.2 Module comments

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 --> means the beginning of the module, <!-- E Comment Text --> means the end of the module, and there is a line between the module and the module.

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 Comments on nested modules

When the module comment appears again in the module comment, in order to highlight the main module, the nested module is no longer used.

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

Instead use

<!-- /Comment Text -->

The comment is written on a separate line at the bottom of the end label of the module.

<!-- 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, on a line alone, with one line separated from line to line.

recommend:

/* Comment Text */ 
.jdc {} 

/* Comment Text */ 
.jdc {}

Not recommended:

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

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

3.2.2 Module comments

The first character and the last character of the comment content are both a space character, / and the module information description occupy one line, multiple horizontal line separators-and / 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

Indicate the page name, author, creation date and other information under the @charset statement of the style file encoding declaration.

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

3.3 JavaScript file comment

3.3.1 Single-line comments

Single-line comments use //. Comments should be written on a single line above the annotated object, not appended to a sentence.

recommend:

// is current tab
const active = true

Not recommended:

const active = true // is current tab

There needs to be a blank line above the comment line (unless the comment line is the top of a block) to increase 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

Multi-line comments use / * ... / instead of multi-line //.

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 increase 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 mark

Sometimes we find a possible bug, but it cannot be fixed for some reasons; or there are still some functions to be completed in a certain place. At this time, we need to use corresponding special mark annotations to inform future self or collaborators. There are two kinds of special marks in common use:

// FIXME: explain what the problem is

// TODO: Explain what else 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 annotations

Document class comments, 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 tool

ESLint is currently the most popular JS code inspection tool. There are some comment-related rules in ESLint, which users can choose to enable:

valid-jsdoc

require-jsdoc

no-warning-comments

capitalized-comments

line-comment-position

lines-around-comment

multiline-comment-style

no-inline-comments

spaced-comment


墨城
1.7k 声望2.1k 粉丝