This paper has participated in theProject Digg”To win a creative gift package and challenge for creative incentive money.
Use these configuration specifications and format your code
In our daily work, we come into contact with all kinds of projects. If the engineering uses different technical architectures, there may be different code specifications. Everyone’s coding habits are different and difficult to change in a short time, which is why we often encounter various specifications reporting errors when developing a new project.
At this point, if we can have a set of configuration that allows us to write code without considering the rules of the project, as long as we save it, we can automatically fix all errors according to the rules configured in the current project, which will undoubtedly greatly increase our development experience and efficiency.
I’ll detail what we need to do in order to achieve this goal, as well as the basic configuration of the various specifications.
EditorConfig
First, we need a basic specification, such as indentation, how to wrap lines, and so on. It needs to work for all teams, for all languages, and for all editors.
Editorconfig helps us do this. It keeps all developers on the same page on basic coding specifications.
What we need to do is:
- The installation
EditorConfig
Plug-ins (some editors support them by defaultEditorConfig
Please refer toThese editors do not require plug-in installation). - configuration
.editorconfig
File.
Here are some examples of.editorConfig usage:
#When you open a file, the EditorConfig plug-in looks for a file named.editorConfig in the directory of the open file and in each parent directory.
## If you reach the root file path or find an EditorConfig file with root=true, the search for the.editorConfig file will stop.
## If root=true is not configured, the EditorConfig plugin will look for the.editorConfig file outside the project
root = true
## use rules to match files
#Matches any string except the path separator (/)
#Matches any string
##? Matches any single character
## [name] matches any single character in the given string
## [! Name] matches any single character that is not in the given string
## {s1,s2,s3} matches any given string
## {num1.. Num2} Matches any integer between num1 and num2, where num1 and num2 can be positive or negative
#Rule [*.{js}] only applies to.js files. In general, our configuration [*] works for all files.
[*]
## Indent method. The value can be TAB or space
indent_style = space
## Indent size. When set to TAB, the value of tab_width is taken.
indent_size = 2
#No setting is usually required. Indent_size takes effect only when indent_size = TAB.
tab_width = 2;
## Set to LF, CR, or CRLF to control how newlines are represented.
end_of_line = lf
#Set to latin1, UTF-8, UTF-8-BOM, UTF-16BE, or UTF-16LE to control the character set.
charset = utf-8
## set to true to remove any space characters before newlines and false to ensure that they do not.
trim_trailing_whitespace = true
## set to true to ensure the file ends with a newline when saved and false to ensure it does not end with a newline.
inset_final_newline = true
Copy the code
Eslint
For front-end developers, JavaScript is our best friend. ESLint, on the other hand, is a plug-in static checking tool for JavaScript code. The core of ESLint is to locate code that does not conform to convention specifications through pattern matching of the AST (Abstract Syntax Tree) derived from code parsing.
There are many different versions of the specification in the community, and each team may create its own. There are thousands of coding styles, and the configuration of the project is a set, in the collaboration of many people will inevitably be the norm error. We need to configure a set of rules so that we don’t need to Care what the rules are and automatically format the code according to the project specifications when saving the file.
What to do?
Eslint provides style guide rules and specifies which are fixable: Stylistic Issues
What we need to do is:
- Install Eslint locally and community recommended specificationseslint-config-airbnb(It can also be another specification). Plugins will use the installed Eslint library (if you haven’t already:
npm i eslint eslint-config-airbnb
). - VSCode installation
Eslint plug-in
. - add
.eslintrc.js
Configuration file. - Change VSCode
setting.json
File configuration.
In order to automatically format according to the rules of the project, the fourth step is essential.
setting.json
If you already have the Eslint plugin installed, press CMD + shif + p to open the defaultsettings. json file and press CMD + f to search Eslint to see all the default configurations of Eslint in VSCode. We need to make some changes to it.
Again, press CMD + Shift + P to open settings.json. This file is a custom configuration file that overrides the configuration of the same name in defaultSettings.json. In this file we’ll make some changes to the configuration of the ESLint plugin to make it look the way we want it to.
First, we want automatic formatting when saving. There are three configurations to achieve this effect:
editor.formatOnSave
+eslint.format.enable
. The former configuration:Save time formatting
, the latter configuration:Use ESlint rules as formatting standards
.eslint.autoFixOnSave
editor.codeActionsOnSave
The second, eslint.autoFixOnSave, has been deprecated. Using it prompts you to change to editor.codeActionsOnSave.
Both the first and the third are possible, but the third editor.codeActionsOnSave is recommended, which supports higher configurability.
When using editor.codeActionsOnSave, we need to disable other formatters, and it is best to set ESlint to the formatter default. And when we do, we can turn off editor.formatonSave, otherwise our file will be repaired twice, which is unnecessary.
Here is what we need to add to setting.json. (Note is the default configuration, no need to add)
// Check when editing or saving, default check when editing. default: onType
// "eslint.run": "onType",
// default: false
// "eslint.format.enable": false,
// default: false
// "editor.formatOnSave": false,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"[vue]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
},
"[javascript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
},
// always display ESLint in the status bar in the lower right corner of VSCode to check the status of ESLint and ensure that ESLint is running properly
"eslint.alwaysShowStatus": true.Copy the code
.eslintrc.js
Next, let’s talk about.eslintrc.js. This file will dictate exactly what rules our ESLint should use to regulate our code.
We usually don’t need to configure this file ourselves, because projects usually have a set of rules configured. We just need to use these rules to format the code.
But it’s also important to understand what each rule means, for example if you want to build a new project yourself.
Next, I’ll look at how to configure.eslintrc.js in terms of common usage, Vue project specific configuration, and React project specific configuration.
Common usage
- By default, ESLint supports ES5 syntax. We can override this configuration to enable ES6, ES7… Support.
// enable es6 syntax and global variable support {env: {es6: true,},}Copy the code
- If we want ESLint to not only recognize syntax in the browser environment,Other environments (Such as
Node
) We also want it to recognize, in which case we can configure it like this:
{
env: {
browser: true,
node: true,
},
}
Copy the code
- In some projects, we need special parsers to parse our code for compliance. We can use Parser
{
parser: 'babel-eslint',
}
Copy the code
- The no-undef rule warns when accessing variables that are not defined in the current source file. If you want to use global variables in a source file, it is recommended that you define these global variables in ESLint so that ESLint does not issue warnings.
{
globals: {
"__DEV__": true,
"If": true,
"For": true,
"POBrowser": true
},
}
Copy the code
- ESLint supportUsing third-party plug-ins. Before using the plug-in, you must install it using NPM. This can be used when configuring plug-ins in the configuration file
plugins
Keyword to hold a list of plug-in names. The plug-in name can be omittedeslint-plugin-
Prefix.
{
plugins: ['react-hooks', 'jsx-control-statements'],
}
Copy the code
- ESLint comes with a lot of rules. You can use comments or configuration filesModify the rules to be used in your project. To change a rule setting, you must set the rule ID to one of the following values:
"off"
或0
– Close rule"warn"
或1
– Enable rules with warning level errors:warn
(Does not cause the program to exit)"error"
或2
– Enable rules, use error level errors:error
(When triggered, the program exits)
{
rules: {
eqeqeq: 'off',
curly: 'error',
quotes: ['error', 'double']
}
}
Copy the code
- When configuring a rule defined in a plugin, you must use it
Plug-in name/rule ID
In the form. Such as:
{
plugins: ['react-hooks', 'jsx-control-statements'],
rules: {
'arrow-parens': 0,
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'warn',
'jsx-control-statements/jsx-use-if-tag': 0,
'react/jsx-no-undef': ['error', { 'allowGlobals': true }],
'no-prototype-builtins': 'off',
}
}
Copy the code
- There are so many rules for ESLint that it would be too much work if we configured them one by one. We can use existing specifications directly.
{
extends: 'zoo/react',
}
Copy the code
Vue
Special configuration
Because of the way Vue single-file components are written, some special ESLint configurations are required for Vue projects to be automated.
Highlight syntax support
Install the Vetur plug-in.
Use ESLint instead of Vetur for code checking
Vetur brings syntax highlighting and ease of operation to Vue projects. But it also automatically turns on code detection for Vue files. This tends to conflict with our configured ESLint. To avoid this, you need to do some configuration in VSCode’s settings.json:
// Do not allow it to format code
"vetur.format.enable": false.// Do not allow it to do code detection
"vetur.validation.template": false."vetur.validation.script": false."vetur.validation.style": false.Copy the code
There is no need to add vue to eslint.validate because eslint.probe will detect VUE type files by default.
Next, we need to configure the.eslintrc.js file, which uses plug-ins that need to be installed locally.
Module. exports = {root: true, // If it is an SSR project, node:true env: {browser: true, node:true,}, // Why parser? https://eslint.vuejs.org/user-guide/#how-to-use-a-custom-parser parser: 'vue-eslint-parser', parserOptions: { parser: 'babel-eslint', }, extends: [// If it is a nuxt.js scaffolding project, Install the appropriate plugin and do the following configuration: '@nuxtjs', 'plugin:nuxt/recommended', // so that ESLint can standardize the vue file 'plugin:vue/base', // vue3 projects need to use it, if vue2 projects, Use plugin:vue/recommended 'plugin:vue/vue3-recommended',], plugins: [// Note that HTML options cannot be configured here, why? https://eslint.vuejs.org/user-guide/#why-doesn-t-it-work-on-vue-files' vue '], / / configure your own rules, covering the above rules of inheritance rules: Indent: ['error', 2, {SwitchCase: 1}], // Use esLint to check the code in template, where I configure 2 Spaces to indent' vue/html-indent': ['error', 2],},};Copy the code
The above configuration, everyone according to their own project characteristics, can be deleted. For example, if your project is not nuxt.js, remove ‘@nuxtjs and Plugin :nuxt/recommended from extends.
If the project is created by the Vue CLI and does not use TS, you need to add the jsconfig.json file to the project root directory. The configuration for jsConfig is here: jsConfig
React
Special configuration
React projects usually do not require special configuration because they are.js files. But even so, there are still a few things we need to do about the JSX and Hooks usage rules
Aiming at the React Hooks
What exactly does the Lint rule enforce?
Eslint-plugin-hooks is a package provided in the React source directory Packages. It enforces the Hooks rule, which is also part of the Hooks API.
npm i eslint-plugin-reack-hooks
Copy the code
In. Eslintrc. Js
Module.exports = {// eslint-plugins: ['react-hooks'],}Copy the code
In view of the JSX
React JSX is just a syntactic sugar for React, which will eventually be called by React. CreateElement compiles the React Element form. So before version 17, if we used JSX but didn’t introduce React, we would say ‘React’ must be in scope when using JSX. After version 17, React works with the Babel and TypeScript compilers, leaving the conversion task to the compiler to automate.
If we were the previous converted version and we wanted syntax support for JSX, we would need to install ESlint-plugin-React, which has code specification checks for JSX built in.
{
extends: ['plugin:react/recommended'],
}
Copy the code
If you don’t want to use the built-in rules, you can also customize the rules
{
plugins: ['react'],
parserOptions: {
ecmaFeatures: {
jsx: true,
},
},
rules: {
'react/jsx-no-undef': ['error', { "allowGlobals": true }],
},
}
Copy the code
If it’s a new transformed version, we need to make a small change so that we don’t have to introduce React when using JSX.
{
extends: ['plugin:react/recommended', 'plugin:react/jsx-runtime'],
}
Copy the code
StyleLint
After the above configuration, we can implement code specification and automatic formatting for.js files, template and script modules of.vue files. However, for.css,.less,.scss files and.vue files, we need to do additional configuration, otherwise the style part is not standard, we can not detect and automatically fix.
What we need to do is:
npm i stylelint stylelint-config-standard stylelint-scss
.- The installation
Stylelint plug-in
. - configuration
.stylelintrc
File. - Configure VSCode
setting.json
File.
Among them, the fourth step is also necessary, we need to do the following configuration:
// Prevent the editor's built-in [CSS] [less] [SCSS] check from reporting the same error as the extension [stylelint]
"css.validate": false."less.validate": false."scss.validate": false.// Save using esLint and stylelint for repair
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true."source.fixAll.stylelint": true
},
// It checks many files by default, this is not necessary, we just let it check the style
"stylelint.validate": [
"css"."html"."less"."postcss"."sass"."scss"."source.css.styled"."styled-css",].Copy the code
Above, our goal has been achieved!
Prettier
Code formatting tool. Many students have been exposed to this tool, I personally have a deep understanding of this tool, the following is my personal opinion. Take an official quote from Prettier.
So why choose the “Prettier style guide” over any other random style guide? Because Prettier is the only “style guide” that is fully automatic. Even if Prettier does not format all code 100% of the Way you’d like, it’s worth the “sacrifice” given the unique benefits of Prettier, don’t you think?
As you can see, this tool is designed to allow different companies and teams to automate save formatting without having to worry about code specifications. Sacrifice personalized content.
But rules are often used inconsistently by different teams, and if you force prettier to be used for automatic formatting of all files, you might run into conflicts with a company-installed code specification checking tool, such as ESLint. ESLint format error even after auto-save.
For prettier to work, we need to configure it in VSCode:
// All files are formatted using prettier
"editor.defaultFormatter": "esbenp.prettier-vscode".// Use prettier only for js files
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
// Automatic formatting is not specified for all files
"editor.defaultFormatter": null.// automatic formatting is not specified for js files
"[javascript]": {
"editor.defaultFormatter": null
}
Copy the code
Prettier can be configured using the. Prettierrc file, setting. Json, editorConfig of VSCode.
Prettier is used to format files that are not commonly used. Js, json, JSX, HTML, CSS, less, vue these documents, such as using engineering unified specification format.
So, I think it’s totally possible to uninstall it. What do you think?
Above is all content, hope to help you ~
Recommended reading
E-commerce minimum inventory – SKU and algorithm implementation
What you need to know about project management
Backflow redraw of browser rendering
Anti-shake throttling scenario and application
Open source works
- Political cloud front-end tabloid
Open source address www.zoo.team/openweekly/ (wechat communication group on the official website of tabloid)
- skuDemo
Open source addressGithub.com/zcy-inc/sku…
, recruiting
ZooTeam, a young passionate and creative front-end team, belongs to the PRODUCT R&D department of ZooTeam, based in picturesque Hangzhou. The team now has more than 50 front-end partners, with an average age of 27, and nearly 30% of them are full-stack engineers, no problem in the youth storm group. The members consist of “old” soldiers from Alibaba and netease, as well as fresh graduates from Zhejiang University, University of Science and Technology of China, Hangzhou Electric And other universities. In addition to daily business docking, the team also carried out technical exploration and practice in material system, engineering platform, building platform, performance experience, cloud application, data analysis and visualization, promoted and implemented a series of internal technical products, and continued to explore the new boundary of front-end technology system.
If you want to change what’s been bothering you, you want to start bothering you. If you want to change, you’ve been told you need more ideas, but you don’t have a solution. If you want change, you have the power to make it happen, but you don’t need it. If you want to change what you want to accomplish, you need a team to support you, but you don’t have the position to lead people. If you want to change the pace, it will be “5 years and 3 years of experience”; If you want to change the original savvy is good, but there is always a layer of fuzzy window… If you believe in the power of believing, believing that ordinary people can achieve extraordinary things, believing that you can meet a better version of yourself. If you want to be a part of the process of growing a front end team with deep business understanding, sound technology systems, technology value creation, and impact spillover as your business takes off, I think we should talk. Any time, waiting for you to write something and send it to [email protected]