1, Naming conventions
Naming conventions commonly used in the market:
- Camel case (small hump Nomenclature - initial lowercase)
- PascalCase (hump Nomenclature - capital letters)
- Kebab case
- Snake (underlined)
1.1 naming of project documents
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. If there is a plural structure, the plural naming method shall be adopted.
Examples: docs, assets, components, directives, mixins, utils, and views.
my-project-name/ |- BuildScript // Pipeline deployment file directory |- docs // Detailed document directory for the project (optional) |- nginx // Front end project nginx agent file directory deployed on container |- node_modules // Downloaded dependent packages |- public // Static page directory |- index.html // Project entrance |- src // Source directory |- api // http request directory |- assets // Static resource directory, where the resources will be built by wabpack |- icon // icon storage directory |- img // Picture storage directory |- js // Public js file directory |- scss // Public style scss storage directory |- frame.scss // Entry file |- global.scss // Common style |- reset.scss // reset styles |- components // assembly |- plugins // plug-in unit |- router // route |- routes // Detailed route splitting directory (optional) |- index.js |- store // Global state management |- utils // Tool storage directory |- request.js // Public request tool |- views // Page storage directory |- App.vue // Root component |- main.js // Entry file |- tests // test case |- .browserslistrc// Browser compatibility profile |- .editorconfig // Editor profile |- .eslintignore // eslint ignore rule |- .eslintrc.js // eslint rule |- .gitignore // git ignore rule |- babel.config.js // babel rule |- Dockerfile // Docker deployment file |- jest.config.js |- package-lock.json |- package.json // rely on |- README.md // Project README |- vue.config.js // webpack configuration
1.1.3 image file name
All are in lowercase. Single word naming is preferred, and multiple word names are separated by underline.
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 naming is preferred, and multiple word names are separated by underline.
|- error_report.html |- success_report.html
1.1.5 CSS file name
All are in lowercase. Single word naming is preferred, and multiple word names are separated by a dash.
|- normalize.less |- base.less |- date-picker.scss |- input-number.scss
1.1.6 JavaScript file name
All are in lowercase. Single word naming is preferred, and multiple word names are separated by a dash.
|- index.js |- plugin.js |- util.js |- date-util.js |- account-model.js |- collapse-transition.js
The above rules can be quickly remembered as "static file underline, compiled file dashes".
1.2 Vue component naming
1.2.1 single file component name
Single file components with a file extension of. vue. Single file component names should always start with uppercase words (PascalCase).
components/ |- MyComponent.vue
1.2.2 single instance component name
Components with only a single active instance should be named with The prefix to show their uniqueness.
This does not mean that the component can only be used for a single page, but_ Each page_ Use only once. These components will never accept any props because they are customized for your application. If you find it necessary to add prop, it indicates that it is actually a reusable component_ Just now_ Use only once per page.
For example, the header and sidebar components are used in almost every page and do not accept prop. This component is specially customized for the application.
components/ |- TheHeading.vue |- TheSidebar.vue
1.2.3 basic component name
Basic components: basic components that do not contain business, independent and specific functions, such as date selector, modal box, etc. As the basic control of the project, such components will be widely used. Therefore, the API of components is abstracted too much, and different functions can be realized through different configurations.
The basic components that apply specific styles and conventions (that is, the components that display classes, are illogical or stateless, and are not doped with business logic) should all begin with a specific prefix - Base. Basic components can be used multiple times in one page and can 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 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, not universal, and will contain some businesses, such as data requests; The basic component contains no business and can be used in any project. It has a single function, such as an input box with data verification function.
Components doped with complex business (with their own data and prop related processing) that is, business components should be named with the prefix Custom. A business component is in a page. For example, there is a card list in a page, and the card whose style and logic are closely related to the business is a business component.
components/ |- CustomCard.vue
1.2.5 tightly coupled component name
Child components closely coupled with the parent component should be named with the parent component name as a prefix. Because editors usually organize files alphabetically, this can put the associated files together.
components/ |- TodoList.vue |- TodoListItem.vue |- TodoListItemButton.vue
1.2.6 word order in component name
Component names should start with high-level (usually general) words and end with descriptive modifiers. Because editors usually organize files alphabetically, the important relationships between components are now clear. 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 search components in the "search" directory and all setting components in the "settings" directory. We only recommend doing this in very large applications (such as 100 + components), because it takes more effort to find between multi-level directories than to scroll through a single component directory.
1.2.7 component name of complete word
Component names should be preferred to abbreviations. Automatic completion in the editor has made the cost of writing long names very low, but the clarity it brings is very valuable. In particular, infrequently used abbreviations should be avoided.
components/ |- StudentDashboardSettings.vue |- UserProfileOptions.vue
1.3 code parameter naming
1.3.1 name
The component name should always be multiple words and should always be PascalCase. Except for the root component and Vue built-in components such as App and. This avoids 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 name should always use camelCase, while kebab case should always be used in templates and JSX. We simply follow the conventions of each language. In JavaScript, camelCase is more natural. 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 regarded as a 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 parsed into user info name: 'UserInfo', component: UserInfo, meta: { title: ' - user', desc: '' } },
1.3.4 components in formwork
For most projects, the component name should always be Pascal case in single file components and string templates, but always kebab case in DOM templates.
<!-- In single file components and string templates --> <MyComponent/> <!-- stay DOM In template --> <my-component></my-component>
1.3.5 self closing assembly
Components without 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/> <!-- Everywhere --> <my-component></my-component>
1.3.6 variables
Naming method: camelCase
Naming convention: type + method of object description or attribute
// bad var getTitle = "LoginTable" // good let tableTitle = "LoginTable" let mySchool = "My school"
1.3.7 constants
Naming method: all uppercase underline split
Naming convention: use capital letters and underscores to combine names, and underscores are used to divide words
const MAX_COUNT = 10 const URL = 'http://test.host.com'
1.3.8 method
Naming method: camelCase
Naming standard: use verb or verb + noun form uniformly
// 1. In general, use the verb + noun form // bad go,nextPage,show,open,login // good jumpPage,openCarInfoDialog // 2. Request data method, ending with data // bad takeData,confirmData,getList,postForm // good getListData,postFormData // 3. Single verb situation init,refresh
verb meaning Return value can Determine whether an action can be performed (power ) Function returns a Boolean value. true: Executable; false: Unenforceable; has Determine whether there is a value Function returns a Boolean value. true: Contains this value; false: Does not contain this value; is Determine whether it is a value Function returns a Boolean value. true: Is a value; false: Not a value; get Get a value Function returns a non Boolean value set Set a value No return value, setting success or chained object
1.3.9 user defined events
Custom events should always use the event name of kebab case.
Unlike components and prop s, there is no automatic case conversion for event names. Instead, the triggered event name needs to exactly match the name used to listen to this event.
this.$emit('my-event') <MyComponent @my-event="handleDoSomething" />
Unlike components and props, event names are not used as JavaScript variable names or property names, so there is no reason to use camelCase or PascalCase. In addition, 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 it impossible for myEvent to be monitored.
Native event reference list [1]
It can be found from the native event 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>
And to distinguish_ Native event_ And_ Custom event_ For the use in Vue, it is suggested that in addition to using kebab case for multi word event names, the naming should also follow the form of on + verb, as follows:
<!-- Parent component --> <div @on-search="handleSearch" @on-clear="handleClear" @on-clickoutside="handleClickOutside"> </div> // Subcomponents 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
Complex computational attributes should be divided into as many simpler attributes as possible. Small, focused computing attributes reduce the hypothetical restrictions on the use of information, so there is no need for so much 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 } }
2.1.5 setting key values for v-for
key must be used with v-for on components to maintain the state of internal components and their subtrees. Even maintain predictable behavior on elements, such as object constancy in animation [2].
<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: Console error --> <ul> <li v-for="user in users" v-if="shouldShowUsers" :key="user.id"> {{ user.name }} </li> </ul>
We tend to do this in two common situations:
To filter 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) to 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 have been hidden (such as v-for = "user in users" v-if = "shouldShowUsers"). In this case, 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 elements of multiple attribute s
The 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
The component template should contain only simple expressions, and complex expressions should be refactored into calculated properties or methods.
Complex expressions can make your template less explicit. We should try to describe what should happen, not how to calculate that value. Moreover, computing properties and methods make the code reusable.
// bad {{ fullName.split(' ').map((word) => { return word[0].toUpperCase() + word.slice(1) }).join(' ') }} Better practices: <!-- In template --> {{ normalizedFullName }} // Complex expression has been moved into a calculated property computed: { normalizedFullName: function () { return this.fullName.split(' ').map(function (word) { return word[0].toUpperCase() + word.slice(1) }).join(' ') } }
2.1.9 quoted attribute value
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 abbreviations of directives
Use: to represent v-bind:
Use @ for v-on:
Use # to represent 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 document template
HTML5 file template:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>HTML5 Standard template</title> </head> <body> </body> </html>
Mobile terminal:
Mobile HTML template<!-- S DNS Pre analysis --> <link rel="dns-prefetch" href=""> <!-- E DNS Pre analysis --> <!-- S For online style page slice development, please directly cancel the annotation reference --> <!-- #include virtual="" --> <!-- E Online style page slice --> <!-- S Local debugging. Select the debugging mode according to the development mode. Please delete it --> <link rel="stylesheet" href="css/index.css"> <!-- /Local debugging mode --> <link rel="stylesheet" href="http://srcPath/index.css"> <!-- /Development machine debugging mode --> <!-- E Local debugging -->
PC end:
<!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 end HTML Template</title> <!-- S DNS Pre analysis --> <link rel="dns-prefetch" href=""> <!-- E DNS Pre analysis --> <!-- S For online style page slice development, please directly cancel the annotation reference --> <!-- #include virtual="" --> <!-- E Online style page slice --> <!-- S Local debugging. Select the debugging mode according to the development mode. Please delete it --> <link rel="stylesheet" href="css/index.css"> <!-- /Local debugging mode --> <link rel="stylesheet" href="http://srcPath/index.css"> <!-- /Development machine debugging mode --> <!-- E Local debugging --> </head> <body> </body> </html>
2.2.2 closure of elements and labels
There are five types of HTML elements:
Empty elements: area, base, br, col, command, embed ded, hr, img, input, keygen, link, meta, param, source, track, wbr
Original text elements: script, style
RCDATA elements: textarea, title
Foreign elements: elements from MathML namespace and SVG namespace
Regular elements: other elements allowed by HTML are called regular elements
In order to enable the browser to better parse the code and make the code more readable, there are the following conventions:
All elements with start and end labels shall be written with start and end labels, and some elements that allow the omission of start labels or bundle labels shall also be written.
Empty element labels are not marked with "/".
<!-- good --> <div> <h1>I am h1 title</h1> <p>I am a text, I have a beginning and an end, and the browser can interpret it correctly</p> </div> <br data-tomark-pass> <!-- bad --> <div> <h1>I am h1 title</h1> <p>I am a text, I have a beginning but no end, and the browser can interpret it correctly </div> <br/>
2.2.3 code nesting
Element nesting specification, each block element has an independent 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 title 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 start writing at the first character of the first line of the style file, with the encoding name of "UTF-8".
recommend: @charset "UTF-8"; .jdc {} Not recommended: /* @charset Rule does not start with the first character on the first line of the file */ @charset "UTF-8"; .jdc {} /* @charset The rule is not in lowercase */ @CHARSET "UTF-8"; .jdc {} /* No @ charset rule */ .jdc {}
2.3.2 code formatting
There are generally two types of style writing: one is Compact format and the other is Expanded format.
Recommended: expand 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, attribute values and keywords are all written in lowercase letters, and attribute strings are allowed to use case.
recommend: .jdc { display: block; } Not recommended: .JDC { DISPLAY: BLOCK; }
2.3.4 code legibility
There is a space between the left parenthesis and the class name, and a space between the colon and the attribute value.
recommend:
.jdc { width: 100%; } Not recommended: .jdc{ width:100%; }
Comma separated values, followed by a space.
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; }
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; }
The color value rgb() rgba() hsl() hsla() rect() does not need spaces, and the value should not have unnecessary 0.
recommend: .jdc { color: rgba(255,255,255,.5); } Not recommended: .jdc { color: rgba( 255, 255, 255, 0.5 ); }
If the hexadecimal value of the attribute value can be abbreviated, use abbreviated as far as possible.
recommend:
.jdc { color: #fff; } Not recommended: .jdc { color: #ffffff; }
Do not specify units for 0.
recommend: .jdc { margin: 0 10px; } Not recommended: .jdc { margin: 0px 10px; }
2.3.5 attribute value quotation marks
When quotation marks are required for CSS attribute values, single quotation marks shall be used uniformly.
recommend: .jdc { font-family: 'Hiragino Sans GB'; } Not recommended: .jdc { font-family: "Hiragino Sans GB"; }
2.3.6 attribute writing suggestions
The following sequence is recommended:
Layout positioning properties: display / position / float / clear / visibility / overflow Self attributes: width / height / margin / padding / border / background Text properties: 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; }
2.3.7 CSS3 browser private prefix
CSS3 browser private prefix comes first and 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 single line code block
Use spaces in single line 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
During programming, curly braces style is closely related to indentation style. There are many methods to describe the position of curly braces relative to code blocks. 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 code
Spaces before and after commas can improve the readability of the code. The team agreed to use spaces after commas and no spaces 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
There cannot be a space between the key and value of an object literal, and a space is required between the colon and value of an object literal.
recommend: var obj = { 'foo': 'haha' } Not recommended: var obj = { 'foo' : 'haha' }
Add a space before the code block.
recommend: if (a) { b() } function a () {} Not recommended: if (a){ b() } function a (){}
A space should be added before the parentheses of a function declaration.
recommend: function func (x) { // ... } Not recommended: function func(x) { // ... }
Spaces are prohibited in function calls.
recommend: fn() Not recommended: fn () fn ()
You need to add spaces before and after the operator.
recommend: var sum = 1 + 2 Not recommended: var sum = 1+2
3, Annotation specification
Purpose of note:
Improve the readability of the code, so as to improve the maintainability of the code
Principles of notes:
As short as possible if not necessary
As long as necessary
3.1 HTML file comments
3.1.1 single line notes
It is generally used for simple descriptions, such as some state descriptions, attribute descriptions, etc.
There is a space character before and after the comment content. The comment is located above the code to be commented and occupies a separate line.
recommend: <!-- Comment Text --> <div>...</div> Not recommended <div>...</div><!-- Comment Text --> <div><!-- Comment Text --> ... </div>
3.1.2 module notes
It is generally used to describe the name of the module and the position where the module starts and ends.
One space character before and after the comment content, Indicates the start of the module, Indicates the end of the module, with one line between 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 notes
When module comments appear again in the module comments, nested modules are no longer used in order to highlight the main modules.
<!-- S Comment Text --> <!-- E Comment Text --> Instead, use <!-- /Comment Text -->
Comments are written on a separate line at the bottom of the tag at the end 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 notes
The first character and the last character of the comment content are a space character, which occupy a separate line, separated by a 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 a space character, / * and module information description occupy one line, multiple horizontal 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 document notes
Note the page name, author, creation date and other information under the style file encoding declaration @ charset statement.
@charset "UTF-8"; /** * @desc File Info * @author Author Name * @date 2015-10-10 */
3.3 JavaScript file comments
3.3.1 single line notes
Single line comments use / /. Comments should be written on a separate line above the annotated object and should not be appended to a statement.
recommend: // is current tab const active = true Not recommended: const active = true // is current tab
An empty line is required above the comment line (unless the top of a block is above the comment line) 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 } // A blank line is not required when the top of a block is above the comment line 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 multiline notes
Multiline comments use / * *... * /, not 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 space
A space is required 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 marks
Sometimes we find a possible bug, but it cannot be fixed for some reasons; or there are some functions to be completed in a certain place. At this time, we need to use corresponding special tag comments to inform ourselves or partners in the future. There are two common special tags:
// 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 notes
Document class annotations, such as functions, classes, files, events, etc.; all use jsdoc specification.
/** * Book Class, representing a book * @constructor * @param {string} title - The title of a book * @param {string} author - The author of a book */ function Book (title, author) { this.title = title this.author = author } Book.prototype = { /** * Get the title of the book * @returns {string|*} */ getTitle: function () { return this.title }, /** * Set the number of pages in the book * @param pageNum {number} the number of pages */ setPageNum: function (pageNum) { this.pageNum=pageNum } }
3.3.6 annotation tools
ESLint is the most popular JS code checking tool at present. There are some annotation related rules in ESLint, 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 to indent and wrap lines.
It is recommended to add a semicolon at the end of JavaScript code for large team multi person collaborative projects.
Small individual innovation and hand training projects can try to use the style without semicolon at the end of JavaScript code, which is more refreshing and concise.