Front-end naming convention
Naming rules
PascalCase: Capitalize the first letter of each individual case
CamelCase: Lowercase the first word and uppercase the rest
Rule: Naming is important for readability and should be as accurate as possible in English
Project named
- The file name must not contain Spaces
- The name must contain lowercase letters and no uppercase letters
- Long names are separated by hyphens (-) and underscores (_)
good:
baidu/fe-team/project-athena
Copy the code
Named after the className
The className name should reflect the function and intent of the element. Avoid obscure names
good:
.header {
font-weight: 600;
color: #000;
}
Copy the code
not good:
.fw-600 {
font-weight: 500;
}
.gray {
color: #ccc
}
Copy the code
constant
Words are capitalized, and words are connected with underscores
good:
const MAX_IMAGE_SIZE = 10 * 1024 * 1024;
Copy the code
not good:
const MaxImageSize = 10 * 1024 * 1024;
const maximagesize = 10 * 1024 * 1024;
const maxImageSize = 10 * 1024 * 1024;
Copy the code
variable
Using camelCase naming method, according to different data types and singular and complex numbers:
- Ordinary variables (
number, string, date
) - Boolean type: Requires a prefix that identifies the meaning of the variable, such as
has, is, wether, can, should
Etc. - Plural forms such as arrays/collections: preferably with
s
orlist
Can identify the suffix end of the plural form, identify the current variable is plural form, improve readability
good:
let isVisited = false;
Copy the code
not good:
let visited = false;
Copy the code
function
Using the camelCase naming method, with the verb + object (verbal-object phrase) way of naming
The verb represents the current action, such as query to query the data, send to send the data, and the object represents the target object, such as queryUsers to retrieve the user collection, and saveUserInfo to save the user information
good:
QueryProductList () {// TODO}Copy the code
not good:
productList() {
// TODO
}
Copy the code
The members of the class
- Public property: the name of the same variable
- Public methods: Named in the same way as functions (
The svo phrases
) - Private properties and methods: The same naming convention as public properties and methods, respectively, but prefixed by
_
function User(name) {
var _name = name; // Private variables
// Public method
this.getName = function() {
return_name; }}const user = new User('lucy');
user.setName('cherry');
const username = user.getName(); // => cherry, output the value of _name
Copy the code
React project structure and component naming
- Target objects: classes and components defined through const
- Naming principle: the name is clear and unique, easy to find, and avoid ambiguity
The directory structure
A complete project will include folders and files such as SRC, public, readme.md,.ignore, package.json, yarn.lock, etc. SRC is the folder where the source code is stored. This article focuses on the directory structure under SRC.
─ SRC │ ├─ containersCopy the code
As shown in the figure above, there are components and containers directories under SRC, which have several problems:
Subjective rules
:componnets
andcontainers
Responsibilities are unclear, team members have subjective differences in their understanding of components and containers, and developers have difficulty consistently approving and judging the two categoriesDynamic changes of components are not taken into account
: Even if a particular type of component is defined, it may change over the life of the project, so the component has to be removed fromcomponnets
andcontainers
Move back and forth betweenComponents of the same name
Components should be named declaratively and uniquely within the project to avoid confusion about the responsibilities of the component. However, the above naming method makes it possible for components to have the same name: one can be a container, and one can be a presentation componentinefficient
: Even if the implementation is a single function, it has to be incomponnets
andcontainers
It’s too common to switch back and forth between directories because one feature contains both container types and presentation components
There is a variation on this approach:
── src
└── User
├── componnets
└── containers
Copy the code
This approach avoids the problem of switching back and forth between distant Componnets and containers directories, but when there are many modules in a project, dozens of Componnets and containers directories, or even more, can be created in the project.
Split and combine code
Under the Components directory, the files are organized in a model/feature structure.
Only one User module is needed to add, delete, modify, and query users, so the directory structure will look like this:
├─ SRC ├─ molecular ├── User ├─ form.jsx ├─ list.jsxCopy the code
When a component has more than one file, we will put the component and its corresponding file in the same folder and name it with the same name. For example, if we have a component form.jsx that references the styles in form.css, the directory structure will look like this:
│ ├─ User ├─ Form │ ├── form.css │ ├── form.jsx ├─ list.jsxCopy the code
UI Component directory
In addition to module partitioning, we will also create a UI directory under the Components directory for common components. Components in the UI directory do not belong to any business module, they should be directly placed in public open source libraries, such as Button, Select, Modal, Input, Checkbox, visual components, etc.
The directory for common components can also be named common
The component named
This is about organizing directories through modules/features, but it’s not about naming directories.
The objects in question are classes and components defined by const:
class MyComponent extends Component {}
const MyComponent = () => {};
Copy the code
As mentioned above, the naming of components should be clear and unique throughout the application to facilitate finding and avoid ambiguity.
Component names are very easy to use when an application has runtime errors or is debugged using the React developer tools, because the component name is always accompanied by the error.
Naming a component can be based on the path naming (*path-based-component-naming*). Naming the component according to the directory in which the component resides. If the component is outside the Components directory, naming the component according to the relative path from the SRC. For example, a component in the components/User/ list.jsx path will be named UserList
If the file that defines a component has the same name as the folder in which it resides, the component name does not need to be repeated. Such as components/User/Form/Form should be named UserForm rather than UserFormForm JSX.
There are several advantages to using the above principles:
Easy to search
If your editor supports fuzzy search, then searchUserForm
You can find the corresponding file
- Searching for files in the directory tree can also be quickly located
- You can avoid duplicate names at introduction
Naming a file based on the component context follows the path-based-component-naming rule. For example, if you know that it is a Form component in the User module, there is no need to repeat the word User in the file name of the Form component. Just use form.jsx.
Using full names for files in a project can lead to the same parts being repeated multiple times and the paths being introduced that are too long. The following example shows the difference:
import ScreenUserForm from './screens/User/UserForm';
// vs
import ScreenUserForm from './screens/User/Form';
Copy the code
A single example doesn’t show a clear advantage, but a small increase in application complexity can make a big difference:
import MediaPlanViewChannel from './MediaPlan/MediaPlanView/MediaPlanViewChannel.jsx';
// vs
import MediaPlanViewChannel from './MediaPlan/View/Channel.jsx';
Copy the code
Now imagine a file name repeated five to ten times.
For these reasons, naming based on the context of the component and the relative path of the component is preferable.
Page (Screen)
To add, delete, modify and check a user, you need to have a user list page, create a user page, and edit an existing user page.
In an application, a page is composed of components. Ideally, the page should contain no logic, just a functional component.
The SRC directory is the root directory and the different pages are scattered in different directories because pages are divided by route definition rather than module.
─ ─ the SRC │ ├ ─ ─ components │ └ ─ ─ screens │ └ ─ ─ the User │ ├ ─ ─ Form. The JSX │ └ ─ ─ the List. The JSXCopy the code
Assuming you are using React-router in your project and you place the root.jsx file under the Screens directory and define the route in it, the root.jsx code might look like this:
import React, {Component} from 'react';
import {Router} from 'react-router';
import {Redirect, Route, Switch} from 'react-router-dom';
import ScreensUserForm from './User/Form';
import ScreensUserList from './User/List';
const ScreensRoot = () = > (
<Router>
<Switch>
<Route path="/user/list" component={ScreensUserList} />
<Route path="/user/create" component={ScreensUserForm} />
<Route path="/user/:id" component={ScreensUserForm} />
</Switch>
</Router>
);
export default ScreensRoot;
Copy the code
Place all pages in the same directory as the route, user/ -> user/. Create a directory for each parent route and organize child routes in this directory. In the example, the User directory is created and the List page and the Form page are placed in it, which makes it easy to locate the currently routed rendered page based on the URL.
You can see that the components imported into the routing file are prefixed with Screen. When creating components outside of the Components directory, they should be named relative to the SRC directory. Located in the SRC/screens/User/List. JSX path components should be named ScreensUserList.
After creating root.jsx, the SRC directory structure looks like this:
─ SRC │ ├ ─ ─ components │ │ ├ ─ ─ the UI │ │ └ ─ ─ the User │ │ ├ ─ ─ Form │ │ │ ├ ─ ─ Form. The CSS │ │ │ └ ─ ─ Form. The JSX │ │ └ ─ ─ the List │ └ ─ ─ Screens │ ├ ─ ─ Root. JSX │ └ ─ ─ the User │ ├ ─ ─ Form. The JSX │ └ ─ ─ the List. The JSXCopy the code
Practical experience
- The Components and Container folders are used to store common components and container components, which can easily lead to confusion of meanings. Inconsistent understanding of names in team cooperation leads to inefficiency and difficulty in finding components
- Components that consist of multiple child components should be stored in the same folder
- Components should have a UI folder for common components unrelated to modules, such as Buttons, Inputs, Checkboxes, Selects, Modals…
Refer to the link
Convex laboratory code specification
Tencent AlloyTeam code specification
Baidu FEX code specification
CodeReview Best Practices
Front-end development specifications: naming specifications, HTML specifications, CSS specifications, JS specifications
React project structure and component naming