In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces how to standardize the configuration of VSCode, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
Use these configuration specifications and format your code
In our daily work, we will come into contact with all kinds of projects. If the technical architecture used by the project is different, there may be different code specifications. And everyone's coding habits are different and difficult to change in a short period of time, which is why we often encounter various specifications reporting errors when developing a new project. [recommended: "vscode tutorial"]
At this time, if we can have a set of configuration, we can write code without considering the rules of the project, and as long as we save it, we can automatically fix all errors according to the rules configured by the current project. This will undoubtedly greatly increase our development experience and efficiency.
Below I will explain in detail what we need to do to achieve this goal, as well as the basic configuration of the various specifications.
EditorConfig
First of all, we need a basic specification, such as indentation, how to wrap, and so on. It should apply to all teams, to all languages, to all editors.
Editorconfig can help us achieve this. It allows all developers to agree on the basic coding specifications.
What we need to do is:
Install the EditorConfig plug-in (some editors support EditorConfig by default, see that these editors do not need to install plug-ins).
Configure the .editorconfig file.
Here are the usage and examples of .editorconfig:
# # when opening 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 be stopped. # # if root=true is not configured, the EditorConfig plug-in will look outside the project for the .editorconfig file root=true # # use the rule matching file # # * to match any string except the path separator (/) # # * * match any string # #? Match any single character # [name] match any single character # [! name] in a given string match any single character # # {S1 Magazine S2 match S3} match any given string # # {num1..num2} match any integer between num1 and num2 Where num1 and num2 can be positive or negative # for example, the rule [*. {js}] only applies to .js files. In general, our configuration [*] takes effect on all files. [*] # indent mode. The value can be tab or spaceindent_style = space## indent size. When set to tab, the value of tab_width is taken. Indent_size = 2 steps # usually does not need to be set. It will not take effect until indent_size = tab. Tab_width = 2positional # is set to lf, cr, or crlf to control how newline characters are represented. End_of_line = lf## is set to latin1, utf-8, utf-8-bom, utf-16be or utf-16le to control the character set. Charset = utf-8## is set to true to remove any space characters before the newline character, and set to false to ensure that it does not. Trim_trailing_whitespace = true## is set to true to ensure that the file ends with a newline character when saved, and set to false to ensure that it does not end with a newline character. Inset_final_newline = true
Eslint
For front-end development engineers, JavaScript is undoubtedly our best partner. And ESLint, it is a plug-in JavaScript code static checking tool, its core is through the code parsing AST (Abstract Syntax Tree, abstract syntax tree) for pattern matching, locate the code that does not conform to the convention specification.
There are many different versions of the specification in the community, and each team may develop its own specification. There are tens of thousands of coding styles, and the configuration of the project is one set, so it is inevitable that the specification will report errors when many people cooperate. We need to configure a set of rules so that we don't need what the Care rules are, and automatically format the code according to the engineering specification when saving the file.
What should I do?
Eslint provides style guide rules and makes it clear what is repairable: Stylistic Issues
What we need to do is:
Install Eslint locally and the community-recommended specification eslint-config-airbnb (which can also be another specification). The plug-in will use the installed Eslint library (if you haven't already installed: npm i eslint eslint-config-airbnb).
VSCode installs the Eslint plug-in.
Add the .eslintrc.js configuration file.
Change the configuration of the setting.json file for VSCode.
Among them, if you want to automatically format according to the rules of the project, the fourth step is necessary.
Setting.json
If you have installed the Eslint plug-in, press cmd + shif + p, open the defaultSettings.json file, press cmd + f to search eslint and you can see the default configuration of all ESlint in VSCode. We need to make some changes to it.
Or press cmd + shift + p to open the settings.json file. This file is a user-defined configuration, and the configuration in it will overwrite the configuration with the same name in defaultSettings.json. We make some changes to the configuration of the ESLint plug-in in this file to make it work the way we want it to.
First, we want to automatically format when we save, and there are three configurations to achieve this effect:
Editor.formatOnSave + eslint.format.enable. The former configuration: formatting on save, the latter configuration: using ESlint rules as the formatting standard.
Eslint.autoFixOnSave
Editor.codeActionsOnSave
Among them, the second kind of eslint.autoFixOnSave has been abandoned. Using it prompts you to change to editor.codeActionsOnSave.
Both the first and the third can be implemented, but a third editor.codeActionsOnSave is recommended, which supports higher configurability.
When using editor.codeActionsOnSave, we need to disable other formatters, and the best thing to do is to set ESlint as the formatter default. And when we do this, we can close editor.formatOnSave, otherwise our files will be repaired twice, which is not necessary.
Here are the configurations we need to add to setting.json. (the comment is the default configuration, which does not need to be added)
/ / detect when editing or when saving. By default, it is detected 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 the word ESLint in the status bar in the lower right corner of VSCode Check the running status of ESLint to make sure that ESLint is running "eslint.alwaysShowStatus": true
.eslintrc.js
Next, let's talk about the .eslintrc.js file. This file will specify exactly what rules our ESLint should use to regulate our code.
We often do not need to configure this file ourselves, because the project usually has a set of rules. We just need to use this set of rules to format the code.
But it is also important for us to understand the meaning of each rule, such as if you want to build your own new project.
Next, I'll look at how to configure the .eslintrc.js file in terms of general usage, Vue project special configuration, and React project special configuration.
Common usage
By default, ESLint supports the syntax of ES5. We can override this configuration and enable ES6, ES7... The support of.
/ / enable support for es6 syntax and global variables {env: {es6: true,},}
If we want ESLint to recognize not only syntax in the browser environment, but also other environments (such as Node), we can configure it like this:
{env: {browser: true, node: true,},}
In some projects, we need a special parser to parse our code to see if it conforms to the specification. We can use Parser at this time.
{parser: 'babel-eslint',}
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 a warning.
{globals: {"_ DEV__": true, "If": true, "For": true, "POBrowser": true},}
ESLint supports the use of third-party plug-ins. Before you can use the plug-in, you must install it using npm. When configuring plug-ins in the configuration file, you can use the plugins keyword to store a list of plug-in names. The plug-in name can omit the eslint-plugin- prefix.
{plugins: ['react-hooks',' jsx-control-statements'],}
ESLint comes with a large number of rules. You can use comments or configuration files to modify 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" or 0-close rule
"warn" or 1-turn on the rule, using a warning-level error: warn (does not cause the program to exit)
"error" or 2-Open the rule, using the error level error: error (when triggered, the program exits)
{rules: {eqeqeq: 'off', curly:' error', quotes: ['error',' double']}}
When configuring a rule defined in the plug-in, you must use the plug-in name / rule ID form. For example:
{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',}}
There are so many rules for configuring ESLint that if we configure them one by one, it will be a lot of work. We can use the existing specifications directly.
{extends: 'zoo/react',}
Vue special configuration
Because of the special writing method of Vue single file component, we need to do some special ESLint configuration for Vue project in order to achieve the effect of automation.
Highlight syntax support
Install the Vetur plug-in.
Use ESLint instead of Vetur for code testing
Vetur brings syntax highlighting and convenient operation to the Vue project. But it also automatically turns on code detection of Vue files. This often conflicts with the ESLint that we configure. To avoid this, you need to do some configuration in VSCode's settings.json:
/ / it is not allowed to format the code "vetur.format.enable": false,// does not allow it to do code detection "vetur.validation.template": false, "vetur.validation.script": false, "vetur.validation.style": false
There is no need to add vue to eslint.validate because eslint.probe detects vue type files by default.
Then, we need to configure the .eslintrc.js file, where all the plug-ins need to be installed locally.
Module.exports = {root: true, / / if it is a SSR project, you need to configure node:true env: {browser: true, node:true,}, / / Why is the parser configuration like this? Https://eslint.vuejs.org/user-guide/#how-to-use-a-custom-parser parser: 'vue-eslint-parser', parserOptions: {parser:' babel-eslint',}, extends: [/ / if it is the scaffolding project of nuxt.js Then you need to install the corresponding plug-in and configure'@ nuxtjs', 'plugin:nuxt/recommended', / / so that eslint can standardize the vue file' plugin:vue/base', / / vue3. If it is a vue2 project, you need to use it. Using plugin:vue/recommended 'plugin:vue/vue3-recommended',], plugins: [/ / Note that the html option cannot be configured here, why? Https://eslint.vuejs.org/user-guide/#why-doesn-t-it-work-on-vue-files' vue',], / / configure your own rules to override the rules inherited above rules: {/ / configure the indentation of js to 2 The case of the switch case statement also uses two spaces to indent indent: ['error', 2, {SwitchCase: 1}], / / use eslint to detect the code in template. Here I configure two spaces to indent' vue/html-indent': ['error', 2],},}
The above configuration can be deleted according to the characteristics of your own project. For example, if your project is not nuxt.js, you can remove'@ nuxtjs and plugin:nuxt/recommended from extends.
If the project is created by Vue cli and does not use ts, you need to add the jsconfig.json file to the root of the project. The configuration of jsconfig is here: jsconfig
React special configuration
In React projects, because they are .js files, there is generally no need for special configuration. But even so, we still need to do something about the rules for the use of JSX and Hooks
For React Hooks
What exactly does the lint rule enforce?
Eslint-plugin-hooks is a package provided in the React source directory packages. It enforces Hooks rules, which are also part of Hooks API.
Npm i eslint-plugin-reack-hooks
In .eslintrc.js
Module.exports = {/ / eslint-plugin can be abbreviated plugins: ['react-hooks'],}
For JSX
JSX is just a syntactic sugar of React, which will eventually be called by React to React.createElement to compile the city 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 worked with the babel and TypeScript compilers to leave the conversion task to the compiler to convert automatically.
If we are the previous converted version, to get syntax support for JSX, we need to install eslint-plugin-react, which has built-in code specification testing for JSX.
{extends: ['plugin:react/recommended'],}
If we do not want to use the built-in rules, we can also customize the rules
{plugins: ['react'], parserOptions: {ecmaFeatures: {jsx: true,},}, rules: {' react/jsx-no-undef': ['error', {"allowGlobals": true}],},}
If it is a new version of the transformation, we need to make a small change so that when using JSX, we are not required to introduce React.
{extends: ['plugin:react/recommended',' plugin:react/jsx-runtime'],}
StyleLint
After completing the above configuration, we can implement code specification and save-time automatic formatting for .js files,. Vue file template and script modules. But for .css, .less, .scss files and .vue files style modules, we also need to do additional configuration, otherwise the style part is not standard, we will not be able to detect and automatically repair.
What we need to do is:
Npm i stylelint stylelint-config-standard stylelint-scss .
Install the Stylelint plug-in.
Configure the .stylelintrc file.
Configure the setting.json file for VSCode.
Step 4 is also necessary, and we need to do the following configuration:
/ prevent the editor's built-in [css] [less] [scss] checksum this extension [stylelint] reports the same error "css.validate": false, "less.validate": false, "scss.validate": false,// saves using eslint and stylelint to repair "editor.codeActionsOnSave": {"source.fixAll.eslint": true, "source.fixAll.stylelint": true}, / / many files are detected by default This is unnecessary, we just let him test the style "stylelint.validate": ["css", "html", "less", "postcss", "sass", "scss", "source.css.styled", "styled-css",]
Above, our goal has been achieved!
Prettier
Code formatting tool. Many students have come into contact with this tool, I personally in-depth understanding of this tool, the following is my personal opinion. Let's first take a look at an official passage 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% 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 automate saving and formatting without thinking about code specifications for different companies and different teams. Sacrifice personalized content.
However, the use of rules by different teams is often inconsistent, and if all files are forced to use prettier automatic formatting, there will be conflicts with company-configured code specification checking tools (such as ESLint). The actual performance is that after the automatic save, the ESLint format error still occurs.
For prettier to take effect, we need to configure it in VSCode:
/ / use prettier to format "editor.defaultFormatter": "esbenp.prettier-vscode", / / use prettier "[javascript]": {"editor.defaultFormatter": "esbenp.prettier-vscode"} / / all files do not specify automatic formatting method "editor.defaultFormatter": null,// js files do not specify automatic formatting method "[javascript]": {"editor.defaultFormatter": null}
You can use the .prettierrc file, VSCode's setting.json, and .editorConfig to configure prettier.
Recommended for infrequently used file types, use prettier to format. These documents, such as js,json,jsx,html,css,less,vue, are formatted using unified engineering specifications.
Thank you for reading this article carefully. I hope the article "how to standardize the configuration of VSCode" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.