This specification is sorted out according to the latest Alibaba front-end specification. If there are any similarities, it is a pure coincidence.
Front end code specification
The purpose of the specification is to write high-quality code, so that your team members are happy every day, and everyone is happy together.
From the beginning of the Ali statute:
----The complexity of modern software architecture needs collaborative development. How to cooperate efficiently? It is difficult to coordinate without rules and regulations. For example, the formulation of traffic regulations ostensibly aims to limit the right to drive, but in fact it is to protect the personal safety of the public
No speed limit, no traffic lights, who dares to drive on the road. For software, appropriate norms and standards are not to eliminate the creativity and elegance of code content, but to limit excessive personalization, work together in a generally recognized unified way, improve collaboration efficiency and reduce communication costs. The blood of the software system flows between the lines of the code. The improvement of quality is to step on as few pits as possible, eliminate repeated pits, and effectively improve the system stability and code quality.
1, Programming protocol
(1) Naming conventions
1.1. 1 project naming
All are in lowercase, separated by the center line.
Positive example: mall management system
Counterexample: mall_management-system / mallManagementSystem
1.1. 2 directory naming
All are in lowercase and separated by a middle dash. When there is a plural structure, the plural naming method shall be adopted, and the plural is not used for abbreviations.
Positive example: scripts / styles / components / images / utils / layouts / demo styles / demo scripts / img / doc
Counter example: script/style/demo_scripts/demoStyles/imgs/docs
[Special] the component directory in the components of VUE project is named with kebab case.
Positive example: head search / page loading / authorized / notice Icon
Counterexample: HeadSearch/PageLoading
[Special] all directories in VUE projects except the components directory are also named with kebab case.
Positive example: page one / shopping car / user management
Counter example: ShoppingCar/UserManagement
1.1. 3. Naming of JS, CSS, SCSS, HTML and PNG files
All are in lowercase and separated by a middle dash.
Positive example: render dom js/signup. css/index. html/company-logo. png
Counter example: renderdom js/UserManagement. html
1.1. 4 naming rigor
It is strictly forbidden to use pinyin and English for naming in the code, and it is not allowed to use Chinese directly. Note: correct English spelling and grammar can make readers easy to understand and avoid ambiguity. Note that even pure Pinyin naming should be avoided
Positive example: henan/luoyang/rmb and other international names can be regarded as English
Counter example: DaZhePromotion [discount] / getPingfenByName() [score] / int a variable = 3
Eliminate completely nonstandard abbreviations and avoid ignorance of meaning:
Counterexample: the "abbreviation" of AbstractClass is named AbsClass; condition "abbreviations" are named condi, and such arbitrary abbreviations seriously reduce the readability of the code.
(2) HTML specification (Vue Template also applies)
1.2.1 HTML type
The document type declaration of HTML5 is recommended:
(it is recommended to use HTML in text/html format. Avoid XHTML. XHTML and its attributes, such as application/xhtml+xml, have limited application support and optimization space in browsers).
specified character code
IE compatibility mode
specified character code
doctype in uppercase
Positive example:
<!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta charset="UTF-8" /> <title>Page title</title> </head> <body> <img src="images/company-logo.png" alt="Company"> </body> </html>
1.2. 2 indent
Indent with 2 spaces (one tab);
Nested nodes should be indented.
1.2. 3 block notes
After each block element, list element and table element, add a pair of HTML comments.
1.2. 4 semantic label
Many semantic tags are added in HTML5, so semantic tags are preferred to avoid a page with div or p tags.
Positive example
<header></header> <footer></footer>
Counterexample
<div> <p></p> </div>
1.2. 5 quotation marks
Use double quotation marks ("") instead of single quotation marks ('').
Positive example: < div class = "box" > < / div >
Counterexample: < div class = "box" > < / div >
(3) CSS specification
1.3. 1 naming
class names are in lowercase letters separated by a middle dash
id is named by hump type
variables, functions, mixtures and placeholder s in scss are named in Hump style
ID and class names always use names that reflect the purpose and purpose of the element, or other common names instead of superficial and obscure names.
Not recommended:
.fw-800 { font-weight: 800; } .red { color: red; }
recommend:
.heavy { font-weight: 800; } .important { color: red; }
1.3. 2 selector
1) Avoid using tag names in CSS selectors
From the principle of separation of structure, expression and behavior, HTML tags in css should be avoided as far as possible, and there will be potential problems if tag names appear in css selectors.
2) Use direct sub selector
Many front-end developers do not use direct sub selectors when writing selector chains
Difference). Sometimes, this can lead to painful design problems and sometimes can be very performance intensive. However, in any case,
This is a very bad practice. If you don't write very general selectors that need to match to the end of the DOM, you should always consider direct sub selectors.
Not recommended:
.content .title { font-size: 2rem; }
recommend:
.content > .title { font-size: 2rem; }
1.3. 3. Try to use abbreviated attributes
Not recommended:
border-top-style: none; font-family: palatino, georgia, serif; font-size: 100%; line-height: 1.6; padding-bottom: 2em; padding-left: 1em; padding-right: 1em; padding-top: 0;
recommend:
border-top: 0; font: 100%/1.6 palatino, georgia, serif; padding: 0 1em 2em;
1.3. 4 each selector and attribute has one row
Not recommended:
button { width: 100px; height: 50px; color: #fff; background: #00a0e9; }
recommend:
button { width: 100px; height: 50px; color: #fff; background: #00a0e9; }
1.3. 5 omit the units after 0
Not recommended:
div { padding-bottom: 0px; margin: 0em; }
recommend:
div { padding-bottom: 0; margin: 0; }
1.3. 6 avoid using ID selector and global label selector to prevent polluting global style
Not recommended:
#header { padding-bottom: 0px; margin: 0em; }
recommend:
.header { padding-bottom: 0px; margin: 0em; }
(4) LESS specification
1.4. 1 code organization
1) Place public files in the style/less/common folder
Example: / / color less,common. less
2) Organize in the following order
1,@import;
2. Variable declaration;
3. Style statement;
@import "mixins/size.less"; @default-text-color: #333; .page { width: 960px; margin: 0 auto; }
1.4. 2 avoid too many nesting levels
Limit nesting depth to 3 levels. For nesting more than 4 levels, re evaluate it. This avoids overly verbose CSS selectors. Avoid a large number of nested rules. When readability is affected, interrupt it. It is recommended to avoid nested rules with more than 20 rows.
Not recommended:
.main { .title { .name { color: #fff; } } } ``` **recommend:** ```css .main-title { .name { color: #fff; } }
(5) Javascript specification
1.5. 1 naming
1) Lowercase hump is used to name lowerCamelCase. The naming in the code cannot be underlined, nor can it end with an underscore or dollar sign
Counterexample: name / name / name$
2) The method name, parameter name, member variable and local variable all use lowerCamelCase style, and must follow the hump form
Positive example: localValue / getHttpMessage() / inputUserId
The method method name must be in the form of verb or verb + noun
Positive example: saveShopCarData /openShopCarInfoDialog
Counter example: save / open / show / go
It is hereby explained that the following five words shall be used for the details of addition, deletion, query and modification, and no other words shall be used (for the purpose of unifying each end)
add / update / delete / detail / get Attachment: verbs commonly used in function method: get obtain/set set up, add increase/remove delete, create establish/destory Destroy, start start-up/stop stop it, open open/close close, read read/write write in, load load/save preservation, begin start/end end, backup backups/restore recovery, import Import/export export, split division/merge merge, inject injection/extract extract, attach Attach/detach be divorced from, bind binding/separate separate, view see/browse browse, edit edit/modify modify, select selection/mark sign, copy copy/paste paste, undo revoke/redo redo, insert insert/delete remove, add join/append add to, clean clear/clear eliminate, index Indexes/sort sort, find lookup/search search, increase increase/decrease reduce, play play/pause suspend, launch start-up/run function, compile compile/execute implement, debug debugging/trace track, observe observation/listen monitor, build structure/publish release, input input/output output, encode code/decode decode, encrypt encryption/decrypt decrypt, compress compress/decompress decompression , pack pack/unpack Unpack, parse analysis/emit generate, connect connect/disconnect to break off, send send out/receive receive, download download/upload upload, refresh Refresh/synchronize synchronization, update to update/revert restore, lock locking/unlock Unlock, check out have sth. signed/check in Check in, submit Submit/commit deliver, push PUSH/pull PULL, expand open/collapse fold, enter get into/exit sign out, abort give up/quit leave, obsolete Abandoned/depreciate waste, collect collect/aggregate gather
3) Constant names are all capitalized, and words are separated by underscores, so as to make the semantic expression complete and clear, and don't be too long
Positive example: MAX_STOCK_COUNT
Counterexample: MAX_COUNT
1.5. 2 code format
1) Indent with 2 spaces
Positive example:
if (x < y) { x += 10; } else { x += 1; }
2) A blank line is inserted between codes with different logic, semantics and businesses to improve readability
Note: in any case, it is not necessary to insert multiple blank lines to separate.
1.5. 3 string
Use single quotation marks (') instead of double quotation marks ("). This is very beneficial in creating HTML strings:
Positive example:
let str = 'foo'; let testDiv = '<div id="test"></div>';
Counterexample:
let str = 'foo'; let testDiv = "<div id='test'></div>";
1.5. 4 object declaration
1) Creating objects with literals
Positive example: let user = {};
Counterexample: let user = new Object();
2) Use literals instead of object constructors
Positive example: VAR user = {age: 0, name: 1, city: 3};
Counterexample:
var user = new Object(); user.age = 0; user.name = 0; user.city = 0;
1.5. 5 use ES6+
You must give priority to the syntax sugar and functions added in ES6 +. This will simplify your program and make your code more flexible and reusable. For example, arrow functions, await/async, deconstruction, let, for... of, etc.
1.5. 6 parentheses
The following keywords must be followed by curly braces (even if the content of the code block is only one line): if, else, for, while, do, switch, try,catch, finally, with.
Positive example:
if (condition) { doSomething(); }
Counterexample:
if (condition) doSomething();
1.5.7 undefined judgment
Never use undefined to judge variables directly; Use typeof and string 'undefined' to judge variables.
Positive example:
if (typeof person === 'undefined') { ... }
Counterexample:
if (person === undefined) { ... }
1.5. 8 condition judgment and circulation can be up to three layers
If conditional judgment can be solved by using ternary operators and logical operators, do not use conditional judgment, but remember not to write too long ternary operators. If there are more than 3 layers, please draw a function and write clear comments.
1.5. 9 conversion naming of this
References to the context this can only be named with 'self'.
1.5. 10. Use console with caution log
Because of console Log heavy use will have performance problems, so use log function cautiously in non webpack projects.
2, Vue project specification
(1) Vue coding basis
Vue project specifications are based on Vue official specifications( https://cn.vuejs.org/v2/style-guide/ )Based on the A specification in, the project development is carried out on it, so all codes comply with the specification.
Please read the Vue official specification carefully and remember that this is the first step.
2.1. 1. Component specification
1) The component name is more than one word.
The component name should always be composed of multiple words (greater than or equal to 2), and the naming convention is KebabCase format.
This avoids conflicts with existing and future HTML elements, because all HTML element names are single words.
Positive example:
export default { name: 'TodoItem' // ... };
Counterexample:
export default { name: 'Todo', // ... } export default { name: 'todo-item', // ... }
2) The component file name is Pascal case format
Positive example:
components/ |- my-component.vue
Counterexample:
components/ |- myComponent.vue |- MyComponent.vue
3) The base component file name starts with base and uses complete words instead of abbreviations.
Positive example:
components/ |- base-button.vue |- base-table.vue |- base-icon.vue
Counterexample:
components/ |- MyButton.vue |- VueTable.vue |- Icon.vue
4) Child components closely coupled with the parent component should be named with the parent component name as a prefix
Positive example:
components/ |- todo-list.vue |- todo-list-item.vue |- todo-list-item-button.vue |- user-profile-options.vue ((complete word)
Counterexample:
components/ |- TodoList.vue |- TodoItem.vue |- TodoButton.vue |- UProfOpts.vue ((abbreviations used)
5) When using components in the Template template, PascalCase mode should be used and self closing components should be used.
Positive example:
<!-- In single file components, string templates, and JSX in --> <MyComponent /> <Row><table :column="data"/></Row>
Counterexample:
<my-component /> <row><table :column="data"/></row>
6) The data of the component must be a function
When using the data attribute in a component (anywhere except new Vue), its value must be a function that returns an object. Because if it is an object directly, the attribute values between subcomponents will affect each other.
Positive example:
export default { data () { return { name: 'jack' } } }
Counterexample:
export default { data: { name: 'jack' } }
7) Prop definitions should be as detailed as possible
Camel case hump naming must be used
Type must be specified
A note must be added to indicate its meaning
Either required or default must be added
If there is a business need, validator validation must be added
Positive example:
props: { // Component status, used to control the color of components status: { type: String, required: true, validator: function (value) { return [ 'succ', 'info', 'error' ].indexOf(value) !== -1 } }, // User level, used to display the number of crowns userLevel: { type: String, required: true } }
8) Scope component styles
Positive example:
<template> <button class="btn btn-close">X</button> </template> <!-- use `scoped` characteristic --> <style scoped> .btn-close { background-color: red; } </style>
Counterexample:
<template> <button class="btn btn-close">X</button> </template> <!-- Not used `scoped` characteristic --> <style> .btn-close { background-color: red; } </style>
9) If there are many feature elements, you should actively wrap.
Positive example:
<MyComponent foo="a" bar="b" baz="c" foo="a" bar="b" baz="c" foo="a" bar="b" baz="c" />
Counterexample:
<MyComponent foo="a" bar="b" baz="c" foo="a" bar="b" baz="c" foo="a" bar="b" baz="c" foo="a" bar="b" baz="c"/>
2.1. 2. Use simple expressions in the template
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.
Positive example:
<template> <p>{{ normalizedFullName }}</p> </template> // 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(' ') } }
Counterexample:
<template> <p> {{ fullName.split(' ').map(function (word) { return word[0].toUpperCase() + word.slice(1) }).join(' ') }} </p> </template>
2.1. All 3 instructions use abbreviations
Abbreviations are recommended for instructions (use: for v-bind:, use @ for v-on:, and use # for v-slot:)
Positive example:
<input @input="onInput" @focus="onFocus" >
Counterexample:
<input v-on:input="onInput" @focus="onFocus" >
2.1. 4. The order of labels shall be consistent
Single file components should always keep the tag order as`
Positive example:
<template>...</template> <script>...</script> <style>...</style>
Counterexample:
<template>...</template> <style>...</style> <script>...</script>
2.1. 5 the key value must be set for v-for
2.1.6 v-show and v-if selection
If you need to switch very frequently during operation, use v-show; If the conditions rarely change at run time, use v-if.
2.1. 7. Internal structure order of script label
Components > props > Data > calculated > watch > Filter > hook functions (hook functions are executed in order) > methods
2.1.8 Vue Router specification
1) Page Jump data transfer uses routing parameters
For page Jump, for example, if page A jumps to page B, the data of page A needs to be transferred to page B. It is recommended to use routing parameters for parameter transfer instead of saving the data to be transferred to vuex, and then take out the vuex data on page B, because if it is refreshed on page B, the vuex data will be lost and the data cannot be displayed normally on page B.
Positive example:
let id = ' 123'; this.$router.push({ name: 'userCenter', query: { id: id } });
2) Use the route lazy load (lazy load) mechanism
{ path: '/uploadAttachment', name: 'uploadAttachment', meta: { title: 'Upload attachments' }, component: () => import('@/view/components/uploadAttachment/index.vue') },
3) Naming conventions in router
The kebab case naming convention is adopted for path and childrenPoints (try to keep the directory structure of vue files consistent, because the directory and file name are kebab cases, so it is easy to find the corresponding files)
The name naming convention adopts KebabCase naming convention and is consistent with the component component name! (to maintain the keep alive feature, keep alive is cached according to the name of the component, so the two must be highly consistent)
// Dynamic loading export const reload = [ { path: '/reload', name: 'reload', component: Main, meta: { title: 'Dynamic loading', icon: 'icon iconfont' }, children: [ { path: '/reload/smart-reload-list', name: 'SmartReloadList', meta: { title: 'SmartReload', childrenPoints: [ { title: 'query', name: 'smart-reload-search' }, { title: 'implement reload', name: 'smart-reload-update' }, { title: 'View execution results', name: 'smart-reload-result' } ] }, component: () => import('@/views/reload/smart-reload/smart-reload-list.vue') } ] } ];
4) path naming convention in router
In addition to the kebab case naming convention, the path must start with /, even the path in children must start with /. The following example
Purpose:
There are often such scenarios: if there is a problem with a page, you need to find the vue file immediately. If it does not start with /, and the path is composed of parent s and children, you may often need to search the router file many times to find it. If it starts with /, you can search the corresponding components immediately
{ path: '/file', name: 'File', component: Main, meta: { title: 'File service', icon: 'ios-cloud-upload' }, children: [ { path: '/file/file-list', name: 'FileList', component: () => import('@/views/file/file-list.vue') }, { path: '/file/file-add', name: 'FileAdd', component: () => import('@/views/file/file-add.vue') }, { path: '/file/file-update', name: 'FileUpdate', component: () => import('@/views/file/file-update.vue') } ] }
(2) Vue project catalog specification
2.2. 1 Foundation
All naming in vue project must be consistent with the back-end naming.
For example, permissions: back-end privilege, front-end router, store, API, etc. must use the word privielevel!
2.2. 2 use Vue cli scaffold
Use vue-cli3 to initialize the project, and the project name follows the naming convention above.
2.2. 3 catalog description
The directory name is in accordance with the above naming specification, in which the components component is named with capital hump, and all other directories except the components component directory are named with kebab case.
src Source directory |-- api All api Interface |-- assets Static resources, images, icons, styles etc. |-- components Common components |-- config configuration information |-- constants Constant information, all items Enum, Global constants, etc |-- directives Custom instruction |-- filters Filters, global tools |-- datas Analog data, temporary storage |-- lib Externally referenced plug-ins store and modify files |-- mock Analog interface, temporary storage |-- plugins Plug in, global use |-- router Routing, unified management |-- store vuex, unified management |-- themes Custom style theme |-- views View directory | |-- role role Module name | |-- |-- role-list.vue role List page | |-- |-- role-add.vue role New page | |-- |-- role-update.vue role Update page | |-- |-- index.less role Module style | |-- |-- components role Module common components folder | |-- employee employee modular
1) api directory
- The naming of files and variables shall be consistent with the back end.
- This directory corresponds to the back-end API interface, and an api js file is created according to the back-end controller. If the project is large, sub directories can be divided according to business and consistent with the back-end.
- The method name in the api should be semantically consistent with the back-end api url as much as possible.
- For each method in the api, add a comment that is consistent with the backend swagger documentation.
Positive example:
Backend url: employeecontroller java
/employee/add /employee/delete/{id} /employee/update
Front end: employee js
// Add employee addEmployee: (data) => { return postAxios('/employee/add', data) }, // Update employee information updateEmployee: (data) => { return postAxios('/employee/update', data) }, // Delete employee deleteEmployee: (employeeId) => { return postAxios('/employee/delete/' + employeeId) },
2) assets directory
assets are static resources, which store static resources such as images, styles and icons. The naming format of static resources is kebab case
|assets |-- icons |-- images | |-- background-color.png | |-- upload-header.png |-- styles
3) components directory
This directory should be divided according to the component directory. The directory is named KebabCase, and the component naming rule is also KebabCase
|components |-- error-log | |-- index.vue | |-- index.less |-- markdown-editor | |-- index.vue | |-- index.js |-- kebab-case
4) constants directory
This directory stores all constants of the project. If constants are used in vue, please use the vue enum plug-in( https://www.npmjs.com/package/vue-enum)
Directory structure:
|constants |-- index.js |-- role.js |-- employee.js
Example: employee js
export const EMPLOYEE_STATUS = { NORMAL: { value: 1, desc: 'normal' }, DISABLED: { value: 1, desc: 'Disable' }, DELETED: { value: 2, desc: 'Deleted' } }; export const EMPLOYEE_ACCOUNT_TYPE = { QQ: { value: 1, desc: 'QQ Sign in' }, WECHAT: { value: 2, desc: 'Wechat login' }, DINGDING: { value: 3, desc: 'Pin login' }, USERNAME: { value: 4, desc: 'User name password login' } }; export default { EMPLOYEE_STATUS, EMPLOYEE_ACCOUNT_TYPE };
5) router and store directories
These two directories must split the business and cannot be put into one js file.
The router should be consistent with the structure in the views as much as possible
store splits different js files according to business
6) views directory
The naming should be consistent with the backend, router, api, etc
PascalCase rules are used for components in components
|-- views View directory | |-- role role Module name | | |-- role-list.vue role List page | | |-- role-add.vue role New page | | |-- role-update.vue role Update page | | |-- index.less role Module style | | |-- components role Module common components folder | | | |-- role-header.vue role Head assembly | | | |-- role-modal.vue role Pop up box component | |-- employee employee modular | |-- behavior-log Behavior log log modular | |-- code-generator Code generator module
2.2. 4 notes
Sort out the places that must be annotated
- Common component instructions
- The interface js file of the api directory must be annotated
- The state, mutation, action, etc. in the store must be annotated
- The template in the vue file must be annotated. If the file is large, add the start end annotation
- methods of vue file. Each method must be annotated
- The data of vue file shall be annotated for unusual words
2.2. 5 others
1) Try not to manipulate DOM manually
Due to the use of vue framework, try to use vue's data-driven to update dom in project development, and try not to operate dom manually (as a last resort), including adding, deleting and changing dom elements, changing styles, adding events, etc.
2) Delete useless code
Due to the use of code version tools such as git/svn, useless codes must be deleted in time, such as some debugged console statements and useless abandoned function codes.
Codeword is not easy. Ask for three connection support online.
Everyone remember to give a praise before collecting! Good articles are worth seeing by more people.
Pay attention to brother Jiang not to get lost and take you to the high-speed programming.
Join Q group and have in-depth communication with more BAT front-line leaders: 1136157571
WeChat official account: Jiang Xiao fish bar free access to advanced front-end learning materials, turn around salary increase 20K