The source of this article is the public number: Programmer succeeded
This article introduces the practical application of code specification unification in our team from the direction of code specification, code inspection, code formatting, and editor automation.
Outline preview
The content presented in this article includes the following aspects:
- Know code conventions
- Formulate and unify norms
- Magic 1: ESLint
- Magic 2: Prettier
- Magic three: VSCode
- Appendix: Naming and Project Structure Specifications
Know code conventions
Consider two questions first:
- What is code specification?
- Why do you need code specifications?
If you are an experienced front-end developer, you must have come into contact with such old projects: variable names are abc
, fds
, or name1
, name2
, which are named with numbers, such variables are not commented, ghosts Don't know what it does.
This kind of code is a typical non-standard code. In addition to making our developers irritable, the most important problem with such code is that it greatly reduces the efficiency of team collaboration and program quality.
In the process of team collaboration, when other people in the group need to use or review your code, and see this situation, in addition to spraying you, they also spend a lot of time understanding what you wrote. At the same time, it is very easy to cause variable conflicts, bring unknown hidden dangers, debugging difficulties and other problems, and even a programmer's coding attitude and professionalism can be seen.
Of course, there are many aspects to code conventions, and variable naming conventions are just the most basic. The more irregularities there are, the lower the quality of the program and the less efficient the teamwork will be.
After understanding the non-standard code and the problems caused by the non-standard code, as front-end architects, we need to think about three questions:
- How to develop norms?
- How to unify the norms of the team?
- How to detect specifications?
Formulate and unify norms
Like the above situation where variables are randomly named, it was very common in early front-end projects.
Due to the scale of the early project and the limited team size, there is no awareness of naming conventions. It seems that there is no big problem in randomly naming, as long as it is not repeated. However, as front-end projects become larger and more complex, and more and more problems caused by non-standardization, this kind of normative awareness has gradually been paid attention to.
After the continuous development of the community, the agreed naming includes the following specifications:
- Underscore naming:
user_name
- Underline naming:
user-name
- Small hump naming:
userName
- Big hump naming:
UserName
With these specifications, developers have a clue when they come up with names. Moreover, these specifications are currently accepted by most developers. If they are not named according to the specifications, they are likely to be complained by colleagues!
After the specification became a general consensus, everyone used different specifications according to their own preferences, and gradually formed their own coding habits. In a team, each developer often has their own coding habits.
However this became a problem again. Take variables as an example: in a team, some people are used to naming variables with underscores, such as user_name
; some people are used to naming variables with camel case, such as userName
. These two naming methods are correct and conform to the specification, but they will cause confusion in the team's code style and cannot be unified.
So why unify?
The benefits of unification are many. For example, we uniformly stipulate: named variables use underscores, and named methods use small camel . Then when working in a team, everyone knows that this is a variable when they see the underscore, and that it is a method when they see a small hump. The code written by ten people is the style of one person, and there is no need to know other coding styles to achieve barrier-free collaboration.
The code of ten people to write the style of one person is ideal, but it is almost impossible to achieve it by supervision and self-consciousness.
How to do it? The following is the focus of this article: three magic tricks to realize the code specification.
Magic 1: ESLint
As mentioned above, team collaborative development projects, due to the different coding habits of each person, will write a variety of codes. Such code is messy and difficult to maintain.
Therefore, we hope to have such a tool that can formulate a relatively complete and comprehensive set of specifications. If everyone's coding does not meet the specifications, the program will warn or even report errors. This tool is used to force team members to follow a unified code style.
There is this tool, we have all heard it, it is the famous ESLint
ESLint has two capabilities:
- Check for code quality , such as if there are variables that are defined but not used.
- Check code style , line breaks, quotes, indentation and other related specifications.
These two capabilities cover almost most of the code specifications, and the specific specifications are configurable, and the team can customize the code style they like.
After customizing the specification, ESLint automatically checks the code for compliance with the specification when the project is run or hot-updated.
asked : What is the difference between ESLint checking and TypeScript checking?
TypeScript will only check for type errors, while ESLint will check for
style errors.
try ESLint
First install under the project:
$ npm install eslint --save-dev
Then run the command to initialize the configuration: eslint --init
eslint
is an interactive command that toggles up and down to select options suitable for the project; when done, the .eslintrc.json
file is generated.
basic configuration
The basic configuration of .eslintrc.json is as follows:
{
"env": {
"browser": true,
"es2021": true,
},
"extends": [
"eslint:recommended"
],
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module",
},
"rules": {},
};
This base configuration contains a set of default recommended configurations defined in the extension eslint:recommended
.
React configuration
On the basis of the default configuration, React also has a set of recommended syntax configuration, which is defined in the plugin plugin:react/recommended
. If your front-end framework is React and you want to define the eslint specification, then add the following configuration marked +
to the basic configuration. :
{
"env": {
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
+ "plugin:react/recommended"
],
"parserOptions": {
+ "ecmaFeatures": {
+ "jsx": true
+ },
"ecmaVersion": 12,
"sourceType": "module"
},
+ "plugins": [
+ "react"
+ ],
"rules": {
}
};
React + TS configuration
For React to support TS, some additional configuration is required:
{
"env": {
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:react/recommended"
+ "plugin:@typescript-eslint/recommended"
],
+ "parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 12,
"sourceType": "module"
},
"plugins": [
"react",
+ "@typescript-eslint"
],
"rules": {
}
};
code inspection
With the specification defined above, let's now write a piece of code and perform specification checking.
Create a new index.js
file and write the content:
const a = '13'
function add() {
return '1'
}
From a js perspective, these two lines of code are fine. Then we run the check command:
$ npx eslint index.js
Then you will see an error in the console:
2:7 error 'a' is assigned a value but never used no-unused-vars
4:10 error 'add' is defined but never used no-unused-vars
2 problems (2 errors, 0 warnings)
The error means that the variable a
and function add
are declared but not used, indicating that the code does not conform to the agreed specification. This exception is also very common, and the above check command is executed when npm run dev
and npm start
are used in the scaffolded project.
ESLint Specification
As mentioned above, ESLint can customize the inspection specification, which is defined under the rules object of the .eslintrc.json
configuration file.
For example, to define the specification, strings must use double quotes:
{
"rules": {
"quotes": ["error", "double"]
}
}
Once defined, ESLint will report an error if you use single quotes for strings in your code.
quotes
represents the quote specification, one of many, and its value is an array.
The first item in the array is the error level, which is one of the following 3 values:
"off" or 0
- Close Specification"warn" or 1
- Warning Level Specification"error" or 2
- Error level specification
The second item of the array is the real specification. For the complete specification, please refer to here
Open the above webpage, and the green check mark indicates that it has been configured. You need to customize it directly in the rules.
Magic 2: Prettier
In the previous step, we used ESLint to implement specification formulation and inspection. When the developer saves a piece of code, the project will automatically execute the eslint
check command to check the code, and check the console output after the exception is detected, and the development can continue after the developer fixes the exception.
If the encoding specification you configure is more complicated and strict, for example, the string must be in single quotes, the end of the code must be a semicolon, the newline must be 2 tabs and no spaces can be used. With such a fine specification, it is inevitable that there will be inconsistencies during the development process. At this time, the console will report frequent errors, and developers will frequently fix a space and a punctuation mark, which is extremely annoying for a long time.
Because of this, although ESLint is enabled by default in projects generated by scaffolding, many people find it annoying and inefficient after using it, so they manually close ESLint.
So, is there a more efficient way to let everyone write code that fully conforms to the specification very quickly?
has it, it is the second trick: Prettier
Prettier is currently the most popular code formatting tool, and its main function is to format code.
What is formatting? Above, we used ESLint to customize the coding standard. When non-standard code is detected, it will prompt an exception, and then we need our developers to manually fix the irregular place according to the prompt.
The power of formatting is to automatically repair according to the specification with one click of the non-standard code.
Sounds very exciting, let's try it.
First install under the project:
$ npm install prettier --save-dev
Then create a new .prettierrc.json
file:
{
"singleQuote": true,
"semi": true
}
This configuration file has the same function as the rules configuration under ESLint above, which is to define code specifications—yes, Prettier also supports defining specifications, and then formats code according to specifications.
List the common specification configurations of Prettier:
{
"singleQuote": true, // 是否单引号
"semi": false, // 声明结尾使用分号(默认true)
"printWidth": 100, // 一行的字符数,超过会换行(默认80)
"tabWidth": 2, // 每个tab相当于多少个空格(默认2)
"useTabs": true, // 是否使用tab进行缩进(默认false)
"trailingComma": "all", // 多行使用拖尾逗号(默认none)
"bracketSpacing": true, // 对象字面量的大括号间使用空格(默认true)
"jsxBracketSameLine": false, // 多行JSX中的>放置在最后一行的结尾,而不是另起一行(默认false)
"arrowParens": "avoid" // 只有一个参数的箭头函数的参数是否带圆括号(默认avoid)
}
After defining the configuration, we write the content in the index.js
file:
const a = "13"
function add() {
return "1"
}
Then run the format command in the terminal:
$ npx prettier --write index.js
After formatting, look at the index.js file as this:
const a = '13';
function add() {
return '1';
}
See the change, the double quotes are automatically turned into single quotes, and the semicolon is automatically added to the end of the line, which is exactly the same as the specification defined in the configuration file.
! Finally, you don't have to manually fix irregular code anymore, you can do it with one command!
The above is to format a file, of course, batch format files are also supported. Batch formatting finds files by fuzzy matching, which is more commonly used. It is recommended to define it in the script script, as follows:
// package.json
"scripts": {
"format": "prettier --write \"src/**/*.js\" \"src/**/*.ts\"",
}
Prettier also supports setting different code specifications for files with different suffixes, as follows:
{
"semi": false,
"overrides": [
{
"files": "*.test.js",
"options": {
"semi": true
}
},
{
"files": ["*.json"],
"options": {
"parser": "json-stringify"
}
}
]
}
asked : What is the difference between ESLint and Prettier?
The same point: both can define a set of code specifications.
The difference: ESLint will prompt errors for non-standard code when checking; while Prettier will format the code directly according to the specification.
Therefore, the specifications defined by ESLint and Prettier must be consistent and cannot conflict with .
Magic three: VSCode
Above, we achieved code specification formulation, code specification checking, and formatting code according to a specification command through ESLint and Prettier, making it very easy to unify team code style.
However, the challenge of breaking through efficiency has no limits. At this time, another friend made a voice: although it is easy, checking the code still depends on the checking command, and the formatting code also depends on the formatting command, which is always not elegant.
Well, not elegant enough, so is there an elegant solution?
The answer is yes. It is our third trick - VSCode
powerful plugin
VSCode is no stranger to our front-end, and it is our daily development weapon. At present, VSCode almost unifies the editor of the front-end circle, which is powerful and highly praised.
Since it can be so widely recognized, it must have its advantages. In addition to being lightweight and fast to start, VSCode's most powerful feature is its rich and diverse plug-ins, which can meet the various needs of different users.
Among many plug-ins, ESLint
is a very powerful one. That's right, this plugin is the plugin of the same name supported by ESLint on VSCode, the first magic trick we mentioned earlier. Screenshot below:
After installing this plugin, the exceptions that previously needed to be checked by executing the eslint command in the terminal are now directly marked on your code!
Even if you type a wrong symbol, the plugin will track your mistakes in real time, and then give flags and exception reminders. This greatly improves the development efficiency, and no longer has to execute commands to check the code, and see who says it is not elegant.
Since the editor has an ESLint plugin, does it also have a Prettier plugin? You guessed it right, of course there is a plug-in, the full name of the plug-in is Prettier - Code formatter
, the screenshot is as follows, just search and install in VSCode.
The Prettier plugin is installed as a formatter for the editor. Right-click formatting in the code, and you can select Prettier to format the current code.
If you want to automate Prettier, you also need to configure it in the editor.
Editor configuration
There is a user settings setting.json
file in VSCode, which saves the user's custom configuration for the editor.
This configuration is very rich, see official website for details. First we set Prettier as the default formatter in this configuration:
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
After setting this step, comes to the point! Let's configure the automatic formatting of the save file again:
{
"editor.formatOnSave": true
}
After the configuration, a magical thing happened: when you finished writing the code and saved it, you found that the file you were editing was immediately formatted. That is to say, whether your code is written according to the specification or not, it will automatically format it into the specification code for you when you save it.
This step is actually to automatically execute the format command when saving the file. Because we configured the default formatter as Prettier above, and now it is equipped with formatting when saving, which is equivalent to connecting the file saving and the prettier
command.
At this point, with the blessing of the three magic skills, we have realized the automatic inspection and automatic formatting of the code. Now you don't need to consider any format specifications when coding. As long as you save it normally, the editor will automatically help you. Do these things well.
Shared editor configuration
Above, after a configuration in the editor, we finally achieved automatic formatting. Now we want to synchronize these settings to other members of the team, what should we do, do we need to reconfigure them one by one?
Don't panic, don't be so troublesome. VSCode's settings are divided into two categories:
- User settings: apply to the entire editor
- Workspace Settings: Apply to the current directory/workspace
The configuration content of these two types is exactly the same, the difference is only a matter of priority. If you open a project directory that contains workspace settings, the workspace settings will override the current user settings.
So to synchronize the settings to other members of the team, we don't need to change the user settings, we just need to create a new workspace setting in the project directory.
Add a workspace setting method: Create a new .vscode/setting.json
file in the project root directory, and write a unified editor configuration here. So we write the above Prettier configuration here to achieve sharing.
Appendix: Naming and Project Structure Specifications
The code specification, code inspection and code formatting are introduced above, and the unified code style is already very comprehensive.
During the team development process, we have also accumulated some specifications that are not written in the configuration file. These specifications are also very important in a team. This part is the sharing of our team norms.
Mainly say two parts: naming convention and project structure specification.
Naming conventions
Naming conventions, as mentioned at the beginning of the article, four naming conventions for variables. But we also have an agreement on which specification to use where.
- Variable naming: underscore
user_id
- CSS-Class naming: dash
user-id
- Method function name: small camel
userId
- JS-Class naming: big hump
UserId
- Folder naming: underscore
user-id
- Component naming under the folder: underline
user-id
- Component export naming: big hump
UserId
Project Structure Specification
The project structure specification mainly refers to the structure organization under the src
folder.
|-- src
|-- index.tsx # 入口文件
|-- assets # 静态资源目录
|-- components # 公共组件目录
| |-- header
| | |-- index.tsx
| | |-- index.less
|-- stores # 状态管理目录,与 pages 结构对应
| |-- admins
| | |-- index.tsx # 状态文件
| | |-- types.ts # 定义状态类型
| |-- index.tsx
|-- pages # 页面目录,与 stores 结构对应
| |-- admins
| | |-- index.tsx
| | |-- index.less
|-- request
| |-- index.ts # axios 实例,全局请求处理
|-- router
| |-- home.tsx
| |-- index.tsx
| |-- root.tsx
|-- styles # 全局样式
| |-- common.less
| |-- index.less
|-- utils # 工具目录
|-- index.ts
Wonderful past
This column will output long-term articles on front-end engineering and architecture, which have been published as follows:
If you like my article, please like and support me! Also welcome to follow my column, thanks 🙏🙏
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。