“This article has participated in the call for good writing activities, click to view: the back end, the big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!”

First, naming conventions

Commonly used naming conventions in the market:

  • camelCase(Small hump nomenclature – lowercase initials)
  • PascalCase(Large hump nomenclature – capital letters)
  • kebab-case(Short horizontal connection)
  • Snake(Underlined)

1.1 Project file naming

1.1.1 the project name

All in lower case, separated by a dash. Example: my project — the name.

1.1.2 directory name

Refer to the project naming rules, when there is a complex structure, use the plural naming method. Examples: docs, assets, Components, directives, mixins, utils, views.

my-project-name/
|- BuildScript    // Pipeline deployment file directory
|- docs           // The project's detailed document directory (optional)
|- nginx          // Front-end project nginx proxy file directory deployed on the container
|- node_modules   // Download the dependency package
|- public         // Static page directory
    |- index.html // Project entry
|- src            // Source directory
    |- api        // HTTP request directory
    |- assets     // Static resource directory, where resources are built by Wabpack
        |- icon   // icon store directory
        |- img    // Image storage directory
        |- js     // Public js file directory
        |- scss   // Public style SCSS directory
            |- frame.scss   // Import file
            |- global.scss  // Public style
            |- reset.scss   // Reset the style
    |- components     / / component
    |- plugins        / / the plugin
    |- router         / / routing
    |- routes         // Detailed route split directory (optional)
        |- index.js
    |- store          // Global state management
    |- utils          // Directory for storing tools
        |- request.js // Common request tools
    |- views          // Page directory
    |- App.vue        / / the root component
    |- main.js        // Import file
    |- tests          // Test case
    |- .browserslistrc// Browser compatible profile
    |- .editorconfig  // Editor configuration file
    |- .eslintignore  // eslint ignores rules
    |- .eslintrc.js   / / eslint rules
    |- .gitignore     Git ignores rules
    |- babel.config.js / / the Babel rules
    |- Dockerfile // Docker deployment file
    |- jest.config.js
    |- package-lock.json
    |- package.json / / rely on
    |- README.md / / project README
    |- vue.config.js / / webpack configuration
Copy the code

1.1.3 Image file name

Select a single word in lowercase and separate multiple words with an underscore.

banner_sina.gif
menu_aboutus.gif
menutitle_news.gif
logo_police.gif
logo_national.gif
pic_people.jpg
pic_TV.jpg
Copy the code

1.1.4 HTML file names

Select a single word in lowercase and separate multiple words with an underscore.

|- error_report.html
|- success_report.html
Copy the code

1.1.5 CSS File name

All the names are lowercase. A single word is preferred and multiple words are separated by a short line.

|- normalize.less
|- base.less
|- date-picker.scss
|- input-number.scss
Copy the code

1.1.6 JavaScript file names

All the names are lowercase. A single word is preferred and multiple words are separated by a short line.

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

The above rule can be quickly remembered as “static file underline, compile file dash”.

1.2 Vue Component Naming

1.2.1 Single file component name

Single-file components with a.vue file extension. Single-file component names should always begin with the word uppercase (PascalCase).

components/
|- MyComponent.vue
Copy the code

1.2.2 Singleton Component name

Components that only have a single active instance should haveThePrefix names to show that they are unique.

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

For example, the header and sidebar components are used on almost every page and do not accept Prop, which is customized for the application.

components/
|- TheHeading.vue
|- TheSidebar.vue
Copy the code

1.2.3 Basic Component names

Base components: independent, functional base components that do not contain business, such as date pickers, modal boxes, etc. This type of component is used heavily as the basic control of the project, so the API of the component is highly abstracted and can be configured differently to achieve different functions.

Underlying components that apply specific styles and conventions (that is, components that present classes, non-logical or stateless, unadulterated with business logic) should all begin with a specific prefix — Base. Base components are highly reusable components that can be used multiple times within a page and reused across different pages.

components/
|- BaseButton.vue
|- BaseTable.vue
|- BaseIcon.vue
Copy the code

1.2.4 Service Components

Business component: Unlike the basic component which only contains a 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 is only used in the current project and does not have generality, and it contains some businesses, such as data requests. The basic component does not contain business and can be used in any project with a single function, such as an input box with data verification function.

Components doped with complex business (with their own data, prop related processing) should be named with the Custom prefix. A business component within a page, for example: a page has a list of cards, and the cards whose style and logic are closely related to the business are business components.

components/
|- CustomCard.vue
Copy the code

1.2.5 Tightly coupled component names

Child components that are tightly coupled to the parent component should be named prefixed with the parent component name. Because editors usually organize files alphabetically, doing so puts related files together.

components/
|- TodoList.vue
|- TodoListItem.vue
|- TodoListItemButton.vue
Copy the code

1.2.6 Word order in component names

Component names should start with high-level (usually generically described) words and end with descriptive modifiers. Because editors usually organize files alphabetically, important relationships between components are now obvious. The following components are mainly used for search and setup functions.

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

There is another multi-level directory approach, putting all search components in the “search” directory and all Settings components in the “Settings” directory. We recommend doing this only for very large applications (such as 100+ components), because it takes more effort to navigate through multiple levels of directories than to scroll through individual components directories.

1.2.7 Full word component names

Component names should be preferred over abbreviations. Autocompletion in editors has made writing long names very cheap, and the clarity it provides is invaluable. Infrequently used abbreviations should be avoided in particular.

components/
|- StudentDashboardSettings.vue
|- UserProfileOptions.vue
Copy the code

1.3 Code parameter naming

1.3.1 name

Component names should always be multiple words and should always be PascalCase. The exception is the root App and Vue built-in components like
and < Component >. This avoids conflicts with existing and future HTML elements because all HTML element names are single words.

export default {
  name: 'ToDoList'.// ...
}
Copy the code

1.3.2 prop

When declaring prop, it should always be named camelCase, and kebab-case should always be used in templates and JSX. We simply follow the conventions of each language, and what’s more natural in JavaScript is camelCase. In HTML it is kebab-case.

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

1.3.3 the router

The Vue Router Path is named in kebab-case format. Words using Snake (e.g. /user_info) or camelCase (e.g. /userInfo) are treated as one word and search engines cannot distinguish semantics.

// bad
{
  path: '/user_info'.// user_info as a word
  name: 'UserInfo'.component: UserInfo,
  meta: {
    title: '- User'.desc: ' '}},// good
{
  path: '/user-info'.// Can be resolved to user info
  name: 'UserInfo'.component: UserInfo,
  meta: {
    title: '- User'.desc: ' '}},Copy the code

1.3.4 Components in a Template

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

<! -- In single-file components and string templates --> 
<MyComponent/>

<! -- In the DOM template --> 
<my-component></my-component>
Copy the code

1.3.5 Self-closing Components

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

<! -- In single-file components and string templates -->
<MyComponent/>

<! -- In all places -->
<my-component></my-component>
Copy the code

1.3.6 variable

  • Naming method: camelCase
  • Naming conventions: The way a type + object is described or an attribute
// bad
var getTitle = "LoginTable"

// good
let tableTitle = "LoginTable"
let mySchool = "My School"
Copy the code

1.3.7 constants

  • Naming method: all uppercase underline split
  • Naming conventions: Use a combination of uppercase letters and underscores to separate words
const MAX_COUNT = 10
const URL = 'http://test.host.com'
Copy the code

1.3.8 method

  • Naming method: camelCase
  • Naming conventions: use verb or verb + noun forms
// 1
// badGo, nextPage, show, open, login// goodJumpPage, openCarInfoDialog// 2, request data method, end with data
// badTakeData, confirmData, getList, postForm// goodGetListData, postFormData// 3Init, refreshCopy the code
The verb meaning The return value
can Determine whether an action can be performed (right) The function returns a Boolean value. True: executable. False: cannot be executed.
has Determines whether a value is present The function returns a Boolean value. True: contains this value. False: does not contain this value.
is Determines whether it is a value The function returns a Boolean value. True: indicates a value; False: not a certain value.
get Get a value The function returns a non-boolean value
set Set a value Returns no value, whether the setting was successful, or the chained object

1.3.9 Custom Events

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

Unlike components and Prop, event names do not have any automated capitalization conversion. Instead, the name of the event that fires needs to exactly match the name used to listen for that event.

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

Unlike components and prop, the event name is not 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 is 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 to listen on.

  • List of native event references

Native events can be used in the following ways:

<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>
Copy the code

In order to distinguish the use of native events and custom events in Vue, it is recommended that in addition to the case of multi-word event names using kebab-case, the name should also be in the form of on + verbs, as follows:

<! -- Parent component -->
<div
  @on-search="handleSearch"
  @on-clear="handleClear"
  @on-clickoutside="handleClickOutside">
</div>
Copy the code
/ / child component
export default {
  methods: {
    handleTriggerItem () {
      this.$emit('on-clear')}}}Copy the code

1.3.10 Event methods

  • Naming method: camelCase
  • Naming specification: Handle + name (optional) + verb
<template>
  <div
    @click.native.stop="handleItemClick()"
    @mouseenter.native.stop="handleItemHover()">
  </div>
</template>

<script>

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

Second, code specification

2.1 the 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>
Copy the code

2.1.2 data

The component’sdataIt has to be a function.

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

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}}}}Copy the code

2.1.4 computed

Complex computed attributes should be split into as many simpler attributes as possible. Small, focused computational attributes reduce the hypothetical constraints on how information can be used, so there is less refactoring when 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
  }
}
Copy the code

2.1.5 forv-forSet the key value

Keys must be paired with V-For on components to maintain the state of internal components and their subtrees. Even maintaining predictable behavior on elements, such as object constancy in animation.

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

2.1.6 v-ifv-forThe mutex

Never give upv-ifv-forIt applies to the same element.

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

We tend to do this in two common situations:

  • To filter items in a list (e.gv-for="user in users" v-if="user.isActive"). In this case, pleaseusersReplace it with a calculated property (e.gactiveUsers) to return the filtered list.
computed: {
  activeUsers: function () {
    return this.users.filter((user) = > {
      return user.isActive
    })
  }
}
Copy the code
<ul>
  <li
    v-for="user in activeUsers"
    :key="user.id">
      {{ user.name }}
  </li>
</ul>
Copy the code
  • To avoid rendering lists that should be hidden (e.gv-for="user in users" v-if="shouldShowUsers"). In this case, pleasev-ifMove to a container element (e.gul.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>
Copy the code

2.1.7 Elements of Multiple Attributes

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"/>
Copy the code
<! -- good -->
<img
  src="https://vuejs.org/images/logo.png"
  alt="Vue Logo">

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

2.1.8 Simple Expressions in templates

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

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

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

Better practice:

<! -- In template -->
{{ normalizedFullName }}
Copy the code
// Complex expressions have been moved to a calculated property
computed: {
  normalizedFullName: function () {
    return this.fullName.split(' ').map(function (word) {
      return word[0].toUpperCase() + word.slice(1)
    }).join(' ')}}Copy the code

2.1.9 Attribute Values With quotation marks

Non-empty HTML feature values should always be double quoted.

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

2.1.10 Instruction abbreviation

  • with:saidv-bind:
  • with@saidv-on:
  • with#saidv-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>
Copy the code

2.2 HTML

2.2.1 File Templates

HTML5 file template:

<! DOCTYPEhtml>
  <html lang="zh-CN">
  <head>
    <meta charset="UTF-8">
    <title>HTML5 standard template</title>
  </head>
  <body>
  </body>
</html>
Copy the code

Mobile client:

<! DOCTYPEhtml>
<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>Mobile HTML template</title>

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

    <! -- S online style page slice, development please directly uncomment reference -->
    <! -- #include virtual="" -->
    <! -- E-style page slice -->

    <! -- S Local debugging, select the debugging mode according to the development mode, please develop delete -->
    <link rel="stylesheet" href="css/index.css">
    <! -- / local debug mode -->

    <link rel="stylesheet" href="http://srcPath/index.css">
    <! -- / developer debug mode -->
    <! -- E Local debugging -->

</head>
<body>
</body>
</html>
Copy the code

PC:

<! DOCTYPEhtml>
<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 side HTML template</title>

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

    <! -- S online style page slice, development please directly uncomment reference -->
    <! -- #include virtual="" -->
    <! -- E-style page slice -->

    <! -- S Local debugging, select the debugging mode according to the development mode, please develop delete -->
    <link rel="stylesheet" href="css/index.css">
    <! -- / local debug mode -->

    <link rel="stylesheet" href="http://srcPath/index.css">
    <! -- / developer debug mode -->
    <! -- E Local debugging -->
</head>
<body>
</body>
</html>
Copy the code

2.2.2 Closing elements and Labels

There are five types of HTML elements:

  • Empty 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: Any other HTML allowed elements are called regular elements

In order for browsers to better parse code and make code more readable, there are conventions like the following:

  • All elements that have a start tag and an end tag should have a start tag, as well as elements that allow the start tag or bundle tag to be omitted.
  • Empty element tags are not marked with a slash character.
<! -- good -->
<div>
    <h1>I'm h1 heading</h1>
    <p>I'm a piece of text, I start and I finish, and the browser interprets it correctly</p>
</div>
	
<br data-tomark-pass>

<! -- bad -->
<div>
    <h1>I'm h1 heading</h1>
    <p>I am a piece of text, I have no end, and the browser can parse it correctly</div>

<br/>
Copy the code

2.2.3 Code nesting

Element nesting specification, each block element a separate line, inline element 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>
Copy the code

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>
Copy the code

2.3 CSS

2.3.1 Style files

The @charset rule must be written in the style file, and the code name must be “UTF-8” at the beginning of the first line of the style file.

  • Recommendation:
@charset "UTF-8";
.jdc {}
Copy the code
  • Is not recommended:
/* @charset rule does not start at the first character on the first line of a file */
@charset "UTF-8";
.jdc {}

/* @charset does not use lowercase */
@CHARSET "UTF-8";
.jdc {}

/* No @charset rule */
.jdc {}
Copy the code

2.3.2 Code Formatting

There are generally two types of style writing: Compact and Expanded.

  • Recommendation: Expanded
.jdc {
  display: block;
  width: 50px;
}
Copy the code
  • Not recommended: Compact format
.jdc { display: block; width: 50px; }Copy the code

2.3.3 Code case

The style selector, attribute name, and attribute value keywords are all written in lower case, and the attribute string is case-sensitive.

  • Recommendation:
.jdc {
  display: block;
}
Copy the code
  • Is not recommended:
.JDC {
  DISPLAY: BLOCK;
}
Copy the code

2.3.4 Code legibility

  1. A space between the open parenthesis and the class name, and a space between the colon and the property value.
  • Recommendation:
.jdc {
  width: 100%;
}
Copy the code
  • Is not recommended:
.jdc{
  width:100%;
}
Copy the code
  1. Comma-separated values, followed by a space.
  • Recommendation:
.jdc {
  box-shadow: 1px 1px 1px # 333.2px 2px 2px #ccc;
}
Copy the code
  • Is not recommended:
.jdc {
  box-shadow: 1px 1px 1px # 333.2px 2px 2px #ccc;
}
Copy the code
  1. Opens a new line for a single CSS selector or new declaration.
  • Recommendation:
.jdc..jdc_logo..jdc_hd {
  color: #ff0;
}

.nav{
  color: #fff;
}
Copy the code
  • Is not recommended:
.jdc..jdc_logo..jdc_hd {
  color: #ff0;
}.nav{
  color: #fff;
}
Copy the code
  1. Color valuergb() rgba() hsl() hsla() rect()“, and do not contain Spaces, and the value does not contain unnecessary zeros.
  • Recommendation:
.jdc {
  color: rgba(255.255.255.5);
}
Copy the code
  • Is not recommended:
.jdc {
  color: rgba( 255.255.255.0.5 );
}
Copy the code
  1. Property value Hexadecimal value can be abbreviated if possible.
  • Recommendation:
.jdc {
  color: #fff;
}
Copy the code
  • Is not recommended:
.jdc {
  color: #ffffff;
}
Copy the code
  1. Don’t be0Specify the unit.
  • Recommendation:
.jdc {
  margin: 0 10px;
}
Copy the code
  • Is not recommended:
.jdc {
  margin: 0px 10px;
}
Copy the code

2.3.5 Attribute Value quotes

Single quotation marks are used for CSS attribute values.

  • Recommendation:
.jdc {
  font-family: 'Hiragino Sans GB';
}
Copy the code
  • Is not recommended:
.jdc {
  font-family: "Hiragino Sans GB";
}
Copy the code

2.3.6 Writing Suggestions for Attributes

The following order is recommended:

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

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

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

  4. Other attributes (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;
}
Copy the code

3.3.7 CSS3 Browser Private Prefix

The CSS3 browser private prefix precedes the standard prefix.

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

2.4 JavaScript

2.4.1 Single-line code block

Use Spaces in single-line blocks of code.

  • Is not recommended:
function foo () {return true}
if (foo) {bar = 0}
Copy the code
  • Recommendation:
function foo () { return true }
if (foo) { bar = 0 }
Copy the code

2.4.2 Curly brace style

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

  • 【 近 】One True Brace Style
if (foo) {
  bar()
} else {
  baz()
}
Copy the code
  • Stroustrup
if (foo) {
  bar()
}
else {
  baz()
}
Copy the code
  • Allman
if (foo)
{
  bar()
}
else
{
  baz()
}
Copy the code

2.4.3 Whitespace in code

  1. Spaces before and after commas improve code readability, and the team agreed to use Spaces after commas and not before commas.
  • Recommendation:
var foo = 1, bar = 2
Copy the code
  • Is not recommended:
var foo = 1,bar = 2

var foo = 1 , bar = 2

var foo = 1 ,bar = 2
Copy the code
  1. There is no space between the key and the value of an object literal, and a space between the colon and the value of an object literal is required.
  • Recommendation:
var obj = { 'foo': 'haha' }
Copy the code
  • Is not recommended:
var obj = { 'foo' : 'haha' }
Copy the code
  1. Add a space before the block.
  • Recommendation:
if (a) {
  b()
}

function a () {}
Copy the code
  • Is not recommended:
if (a){
  b()
}

function a (){}
Copy the code
  1. Function declarations are preceded by Spaces.
  • Recommendation:
function func (x) {
  // ...
}
Copy the code
  • Is not recommended:
function func(x) {
  // ...
}
Copy the code
  1. Disallow whitespace during function calls.
  • Recommendation:
fn()
Copy the code
  • Is not recommended:
fn ()

fn
()
Copy the code
  1. You need to add Spaces before and after the operator.
  • Recommendation:
var sum = 1 + 2
Copy the code
  • Is not recommended:
var sum = 1+2
Copy the code

3. Annotation specification

Purpose of comments:

  • Improve the readability of your code, thereby increasing the maintainability of your code

Principles of annotation:

  • As short As possible

  • Be As detailed As necessary.

3.1 HTML file comments

3.1.1 Single-line comments

Generally used for simple description, such as some state description, attribute description, etc.

Comment content is preceded by a space character, comment above the code to comment, a single line.

  • Recommendation:
<! -- Comment Text -->
<div>.</div>
Copy the code
  • Is not recommended
<div>.</div><! -- Comment Text -->

<div><! -- Comment Text -->.</div>
Copy the code

3.1.2 Module notes

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

Comment content before and after a space character,

Indicates the end of the module.

  • Recommendation:
<! -- 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 -->
Copy the code
  • Is 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 -->
Copy the code

3.1.3 Nested module comments

When a module comment reappears in a module comment, nested modules are not used in order to highlight the main module.

<! -- S Comment Text -->
<! -- E Comment Text -->
Copy the code

And use

<! -- /Comment Text -->
Copy the code

Comments are written on a single line at the bottom of the module 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 -->
Copy the code

3.2 CSS File Comments

3.2.1 Single-line comment

The first and last character of a comment is a space character on a single line separated by one line.

  • Recommendation:
/* Comment Text */ 
.jdc {} 

/* Comment Text */ 
.jdc {}
Copy the code
  • Is not recommended:
/*Comment Text*/
.jdc {
  display: block;
}

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

3.2.2 Module notes

The first and last character of the comment content is a space character, /* is on one line with the module information description, multiple horizontal delimiters – and */ are on one line, and lines are separated by two lines.

  • Recommendation:
/* Module A
---------------------------------------------------------------- */
.mod_a {}


/* Module B
---------------------------------------------------------------- */
.mod_b {}
Copy the code
  • Is not recommended:
/* Module A ---------------------------------------------------- */
.mod_a {}
/* Module B ---------------------------------------------------- */
.mod_b {}
Copy the code

3.2.3 File Comments

Under the style file encoding declaration @charset, specify the page name, author, creation date, and so on.


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

3.3 JavaScript File comments

3.3.1 Single-line comments

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

  • Recommendation:
// is current tab
const active = true
Copy the code
  • Is not recommended:
const active = true // is current tab
Copy the code

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

  • Recommendation:
function getType () {  
  console.log('fetching type... ')
  
  // set the default type to 'no type'
  const type = this.type || 'no type'
  return type
}
Copy the code
A blank line is not required when the comment line is the top of a block
function getType () {  
  // set the default type to 'no type'
  const type = this.type || 'no type'			
  return type
}
Copy the code
  • Is not recommended:
function getType () {  
  console.log('fetching type... ')
  // set the default type to 'no type'
  const type = this.type || 'no type'
  return type
}
Copy the code

3.3.2 Multi-line comments

Multi-line comments using /**… */ instead of multiple lines //.

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

  return element
}
Copy the code
  • Is not recommended:
// make() returns a new element
// based on the passed in tag name
function make (tag) {
  // ...

  return element
}
Copy the code

3.3.3 Comment space

A space is required between the comment content and the comment character to increase readability. Eslint: spaced – the comment.

  • Recommendation:
// is current tab
const active = true

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

  return element
}
Copy the code
  • Is 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
}
Copy the code

3.3.4 Special Marks

Sometimes we find a possible bug, but for some reason we can’t fix it. Or there may be some unfinished functionality somewhere, in which case we need to use corresponding special markup comments to inform future partners or ourselves. There are two kinds of special tags commonly used:

  • // FIXME: What is the explanatory problem

  • // TODO: describe what else TODO or the solution to the problem

class Calculator extends Abacus {
  constructor () {
    super(a)// FIXME:Shouldn't use a global here
      total = 0

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

3.3.5 Document Comments

Document-class comments, such as functions, classes, files, events, etc. Both use the JSDOC specification.

/** * Book class, representing a Book. *@constructor
 * @param {string} title-Book title. *@param {string} author- The author of the book. */
function Book (title, author) {
  this.title = title
  this.author = author
}

Book.prototype = {
  /** * Gets the title of the book *@returns {string|*}* /
  getTitle: function () {
    return this.title
  },
  /** * Sets the number of pages in the book *@param PageNum {number} Number of pages */
  setPageNum: function (pageNum) {
    this.pageNum=pageNum
  }
}
Copy the code

3.3.6 Annotation Tools

ESLint is one of the most popular javascript code checking tools. ESLint has several comment rules that you can optionally enable:

  • valid-jsdoc

  • require-jsdoc

  • no-warning-comments

  • capitalized-comments

  • line-comment-position

  • lines-around-comment

  • multiline-comment-style

  • no-inline-comments

  • spaced-comment

Four, other

  • Please use two Spaces for indent newlines.
  • A semicolon at the end of JavaScript code is recommended for large team, multi-person collaborative projects.
  • Small personal innovation projects can try to use JavaScript code without semicolons at the end of the style, more clean and concise.