This article takes the VS Code editor as an example, and you can practice it with the example of vscode-linter-example .
Before the article starts, think about a question: Who controls the indented code style of 2 spaces or 4 spaces? VS Code default settings? Or Prettier? Or something else?
Let's start this article with a question.
VS Code editor itself configuration
There are three forms of VS Code configuration: global default configuration, user configuration, and workspace configuration.
- Global default configuration: After VS Code is installed, there will be a
settings.json
configuration file in the installation directory. - User configuration: corresponds to the
settings.json
configuration file in the specific folder associated with the current user in the software directory (similar to $HOME/Library/Application Support/Code/User/settings.json in macOS) , the user configuration takes effect in all open windows. The setting opened byctrl/cmd + ,
b39ced65b80f789902a28de9620b883f--- is the UI view of the user configurationsettings.json
. - Workspace configuration: also known as project configuration, at this time
settings.json
stored in the root directory of the project.vscode
file, when the project is opened in VS Code, it is only opened for the current project window takes effect.
These three forms of configuration priority: Project Configuration > User Configuration > Global Default Configuration.
If there are multiple configurations, the ones with higher priorities will cover the ones with lower priorities. The advantage of this is that different configurations can be made for different projects and different users without interfering with each other, and the project configuration is specific to the project, which is convenient for developers to It can be shared among different developers to achieve the purpose of unifying the development environment and coding style.
VS Code's .vscode
folder
The .vscode
folder in the project root directory, in addition to storing the project configuration, there are other configurations.
.vscode
The configuration contained in the folder:
-
settings.json
-
extensions.json
-
tasks.json
-
launch.json
settings.json
You can use the editor's own default formatter to unify the coding style in this project configuration file, which is also the most basic format.
Common configuration
{
"editor.formatOnSave": true, //保存时自动格式化代码
// 根据打开文件的内容自动检测缩进,会覆盖默认缩进设置,相关设置: #editor.tabSize#和#editor.intertSpaces#
// 例如虽然下面设置的 tabSize 为 4,但是当前文件打开时是文件内容的 tabSize 为 2,所以依然会沿用 2,如果设置为 false,后续的 tabSize 则会使用 4
"editor.detectIndentation": false,
"editor.insertSpaces": true, //是否使用空格
"editor.tabSize": 4, // 空格或者制表符的大小
"editor.fontSize": 14, // 编辑器字体大小
"editor.rulers": [80, 100], // 垂直标尺,会在指定列号处显示竖线
"editor.wordWrap": "wordWrapColumn", // 控制换行方式
"editor.wordWrapColumn": 100 // 控制换行的宽度
}
block file
During project development, some generated intermediate files or some configuration files that are not expected to be changed by ordinary project developers can be configured in settings.json
to shield these files.
{
// 搜索文件时不希望查找的文件
"search.exclude": {
"**/node_modules": true,
"**/bower_components": true,
"**/*.code-search": true
},
// 不想展示的文件
"files.exclude": {
"**/.git": true,
"**/build": true,
"**/deploy.sh": true
}
}
Other configuration
{
// 额外补充一下,VS Code 默认支持 TS,并且可以切换使用项目安装的 TypeScript 版本提供的语法解析和类型检测服务
"typescript.tsdk": "node_modules/typescript/lib"
}
extensions.json
The eslint and prettier plugins that will be used later can be directly added to extensions.json
for the convenience of other developers to install.
{
// 每一项都是一个插件 ID
"recommendations": [
"dbaeumer.vscode-eslint", // eslint 插件ID,下面会讲到此插件
"esbenp.prettier-vscode", // prettier 插件ID,下面会讲到此插件
"EditorConfig.EditorConfig", // EditorConfig 插件ID,下面会讲到此插件
"octref.vetur",
"formulahendry.auto-close-tag",
"formulahendry.auto-rename-tag"
]
}
After the configuration is complete, the project developer will receive a recommendation reminder from VS Code when opening the project for the first time, and can perform one-click installation. If you miss this reminder, you can also filter out the recommended plugins for one-click installation in the plugin options in the sidebar.
Regarding task-related tasks.json
and debugging-related launch.json
, we will have a chance to talk later.
EditorConfig
EditorConfig is used to help developers define and maintain coding style (such as indentation style, end-of-line characters, etc.), EditorConfig contains a custom file for defining code format .editorconfig
and a batch of editor plugins , these plugins allow editors to use custom configuration files and format code accordingly.
After using EditorConfig, the editor's behavior will be the same as defined in the .editorconfig
file, and its priority is higher than the editor's own settings (compared to the VS Code's own configuration priority mentioned in the previous section) high). Some editors support EditorConfig by default, such as WebStorm; while some editors need to install EditorConfig plug-ins, such as Sublime, VS Code, etc. (so it can take effect across editors).
VS Code installation is very simple, just search for EditorConfig for VS Code installation in the plugin market and restart the editor.
When opening a file, the EditorConfig plugin will look for the .editorconfig
file in the opened file's directory and its parent directories, until a configuration file appears root=true
.
The configuration file of EditorConfig is read from top to bottom, and the most recent .editorconfig
will be read first, and the configuration items matching .editorconfig
will be applied in the order of reading, If .editorconfig
file does not have some configuration, the editor default settings are used.
config .editorconfig
Filenames match:
* 匹配除/之外的任意字符串
** 匹配任意字符串
? 匹配任意单个字符
[name] 匹配name字符
[!name] 不匹配name字符
{s1,s2,s3} 匹配给定的字符串中的任意一个(用逗号分隔)
{num1..num2} 匹配num1到num2之间的任意一个整数, 这里的num1和num2可以为正整数也可以为负整数
Common properties:
root : 表示是最顶层的配置文件,发现设为true时,才会停止查找上级的.editorconfig文件
indent_style : 设置缩进风格(tab是硬缩进,space为软缩进)
indent_size : 用一个整数定义的列数来设置缩进的宽度,如果indent_style为tab,则此属性默认为tab_width
tab_width : 用一个整数来设置tab缩进的列数。如果indent_style为space,默认是indent_size
end_of_line : 设置换行符,值为lf、cr和crlf
charset : 设置编码,值为latin1、utf-8、utf-8-bom、utf-16be和utf-16le,不建议使用utf-8-bom
trim_trailing_whitespace : 设为true表示会去除行尾空格
insert_final_newline : 设为true表示使文件以一个空白行结尾
max_line_length : 最大行宽(vscode 不支持)
curly_bracket_next_line : 设为false表示大括号不另起一行(vscode 不支持)
spaces_around_operators : 设为true运算符两边都有空格(vscode 不支持)
quote_type : 设置字符串的引号类型,single是单引号,double是双引号(vscode 不支持)
Base libraries and built-in object instances used
After installing the EditorConfig plugin, and creating and improving the .editorconfig
custom rule, the rules in .editorconfig
will override the corresponding configuration in VS Code user/workspace settings.
For example an example .editorconfig
:
root = true
[*]
charset = utf-8
[*.{js,jsx,ts,tsx,vue}]
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
insert_final_newline = true
EditorConfig can only simply configure some rules, and cannot fully meet the needs. It only serves as a bottom-line configuration for unifying coding style across editors and IDEs . If you want to achieve a good code specification and unification of coding style, you need to configure other codes. Inspection and formatting tools are used, such as: ESLint and Prettier.
ESLint
ESLint is a plug-in JavaScript code static inspection tool. Its core is to perform pattern matching on the AST (abstract syntax tree) obtained by parsing JavaScript code through Espree (default parser) (each rule will monitor the matching process, Whenever a type is matched, the corresponding rules will be checked), analyzing the code to achieve the ability to check code quality and coding style, and some lint rules can avoid the generation of bugs, on the premise of improving code readability and maintainability Next, reduce the number of questions.
Code inspection is a static analysis, often used to find problematic patterns or code, and is not tied to a specific coding style. Code inspections are available for most programming languages, and generally compilers have built-in inspection tools.
There are several reasons for the success of ESLint:
- The default parser can be replaced by another parser, as long as its output is compatible with Esprima (or Espree);
- Scalability is the key
- The rules are set to be fully configurable, meaning you can turn off each rule and run just the basic syntax validation, or mix the rules that are bound by ESLint by default with your custom rules
ESLint command line
Initialize ESLint
npm install eslint -D
npx eslint --init
When eslint is initialized, it will ask how to configure it. For specific questions and options, please refer to: https://github.com/eslint/eslint/blob/v6.0.1/lib/init/config-initializer.js#L422 .
After eslint is initialized, a .eslintrc.js
file will be generated in the root directory of the folder.
Run npx eslint .
to verify all files in the folder.
Running npx eslint . --fix
fixes the problem in the file
VS Code uses the ESLint plugin
The way to use the ESLint command line is an active compilation action. This action is not destined to be frequent, but no one wants to write hundreds of lines of code. After running ESLint verification, it is found that there are n warnings and errors, so in the process of coding It is necessary to see the verification results in real time.
You can install the ESLint plug-in in VS Code, so that the editor can prompt warnings and errors in real time, without having to wait for the prompt when compiling.
Of course you can also enable "Auto Repair On Save" for ESLint:
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
The VS Code plugin requires that the ESLint related plugins and configurations of the local project exist (dependencies, configuration files), but do not necessarily need to be compiled.
Since the ESLint plugin is used in VS Code to prompt warnings and errors in real time, is it possible to use ESLint on the command line?
The answer is that ESLint from the command line is still needed, because there is no guarantee that all developers of the project use VS Code, or it is also possible to manually turn off the ESLint plug-in. In any case, the code submitted to the warehouse must conform to the unified code specification and Coding style, so an ESLint check must be performed before submitting to the repository.
ESLint configuration item resolution
ESLint 的配置文件命名eslintrc.js
、 eslintrc.yaml
、 eslintrc.json
,甚至配置在package.json
中的eslintConfig
Attributes. However .eslintrc
this configuration file naming is said to be deprecated.
It can be seen from the source code that the priority of the configuration file is as follows:
const configFilenames = [
.eslintrc.js ,
.eslintrc.cjs ,
.eslintrc.yaml ,
.eslintrc.yml ,
.eslintrc.json ,
.eslintrc ,
package.json
];
The following is a more comprehensive configuration item analysis:
- ESLint configuration item resolution
- Parse package name of ESLint
- ESLint configuration file.eslintrc parameter description
Parser (parse)
Briefly talk about the three parsers:
-
espree
: ESLint default parser - @babel/eslint-parser : can check all valid babel code, that is, ES6+ code and those experimental grammars can also be used with ESLint
- @typescript-eslint/parser : This parser converts
TypeScript
into a format compatible withespree
, allowing ESLint to validateTypeScript
source code.
By the way, is ESLint's default parser Esprima or Espree? The earliest version of ESLint used the default parser to use the open source Esprima, but when ESLint planned to support ES6 and JSX, it was found that Esprima was not maintained frequently and did not plan to release support for ES6. After many investigations, I finally chose to implement my own parser. It is Espree, and now the default parser of ESLint is Espree.
extensions
Extensions can share configuration, and can modify rules to overwrite unneeded configuration.
Briefly talk about a few common extensions:
- eslint-config-airbnb : Provides all Airbnb ESLint configuration.该配置包含了React 相关的ESLint 规则,
eslint-plugin-import
,eslint-plugin-react
,eslint-plugin-react-hooks
,eslint-plugin-jsx-a11y
这四个插件,并且It does not support React Hooks rules, if you want to support it, you need to enableeslint-config-airbnb/hooks
this extension. - eslint-config-airbnb-base : does not contain React rules, generally used for server-side checks
- eslint-config-prettier : Disable all ESLint rules that are not necessary or conflict with prettier, so as to avoid other shared configurations affecting the formatting of Prettier. Note that this extension only turns off the rules involved, so it only makes sense when used with other configurations. For example
extends: ["eslint:recommended", "prettier"]
, the prettier is written at the end, and the later rules will overwrite the earlier ones.
Plugins
Briefly talk about a few common plugins:
- @babel/eslint-plugin :
@babel/eslint-parser
Parser-partner plugin, in order to support ES6+ code,@babel/eslint-plugin
reimplemented the problematic rules to avoid false positives. - eslint-plugin-import : The purpose of this plugin is to support checking ES6+
import/export
syntax, and also to avoid misspellings in file paths and import names - eslint-plugin-jsx-a11y : Check accessibility of JSX elements
- eslint-plugin-react :
React-specific validation rule plugin - @typescript-eslint/eslint-plugin : Provides inspection rules for TypeScript code
- eslint-plugin-prettier : Make ESLint and Prettier have good cooperation, the main function of this plugin is to use
prettier
as the rules of ESLint, which is equivalent to reporting an ESLint error when the code does not meet the standards of Prettier , and can also be formatted byeslint --fix
. It is equivalent to integrating Prettier into ESLint.
rules
Focus on the rules of ESLint. Officially recommended rules can be used "extends": ["eslint:recommended"]
to open the recommended rules, click to view the detailed document .
ESLint's rule prompt levels:
-
off
or 0: close the rule -
warn
or 1: enable the rule, the warning level error is only a warning, and will not cause the program to exit -
error
or 2: open the rule, when the error of error level is triggered, the program will be launched
ESlint's rules themselves can be divided into two categories:
- The rule has no attribute, just control whether it is turned on or off, for example:
"eqeqeq": "off"
turn off congruence check - Rules have their own properties, for example:
"quotes": ["error", "double"]
One more important point, we can configure any desired rules through rules
this configuration item, it will override the configuration items introduced in extends
and plugins
, That is to say, the rules configured in .eslintrc.*
in rules
have high priority.
Sometimes we need to use custom rules. The implementation of custom ESLint rules mainly lies in understanding the structure of a rule:
For example: no-with
module.exports = {
// 包含规则的元数据,包括规则的类型,文档,是否推荐规则,是否可修复等信息
meta: {
// 指示规则的类型,值为 "problem"、"suggestion" 或 "layout"
type: 'suggestion',
docs: {
// 对 ESLint 核心规则来说是必需的
description: 'disallow `with` statements', // 提供规则的简短描述在规则首页展示
// category (string) 指定规则在规则首页处于的分类
recommended: true, // 配置文件中的 "extends": "eslint:recommended"属性是否启用该规则
url: 'https://eslint.org/docs/rules/no-with', // 指定可以访问完整文档的 url
},
// fixable 如果没有 fixable 属性,即使规则实现了 fix 功能,ESLint 也不会进行修复。如果规则不是可修复的,就省略 fixable 属性。
schema: [], // 指定该选项 这样的 ESLint 可以避免无效的规则配置
// deprecated (boolean) 表明规则是已被弃用。如果规则尚未被弃用,你可以省略 deprecated 属性。
messages: {
unexpectedWith: "Unexpected use of 'with' statement.",
},
},
// create (function) 返回一个对象,其中包含了 ESLint 在遍历 js 代码的抽象语法树 AST (ESTree 定义的 AST) 时,用来访问节点的方法。入参为该节点。
create(context) {
// 如果一个 key 是个节点类型或 selector,在 向下 遍历树时,ESLint 调用 visitor 函数
// 如果一个 key 是个节点类型或 selector,并带有 :exit,在 向上 遍历树时,ESLint 调用 visitor 函数
// 如果一个 key 是个事件名字,ESLint 为代码路径分析调用 handler 函数
// selector 类型可以到 estree 查找
return {
// 入参为节点node
WithStatement(node) {
context.report({ node, messageId: 'unexpectedWith' })
},
}
},
}
To develop a custom rule, you can check the official documentation: https://eslint.org/docs/latest/developer-guide/working-with-rules .
There are several articles on developing plugins or introducing the principles of ESLint to look at:
Several unusual configurations
- overrides : The rules we configure in the rules of
.eslintrc.*
generally take effect globally, and overrides can override some rules for some files. - settings : Through settings, you can pass in some custom configuration content like each rule.
ESLint Detection Profile Steps
- First check whether there is inline configuration, if it is the command line, check whether there are configuration parameters
- Look for
.eslintrc.*
andpackage.json
in the same directory as the file to be detected - Then look in the parent directory, always find the root directory of the file system
- If you find the configuration of
root: true
in the first two steps, stop looking for.eslintrc.*
in the subdirectory - If none of the above steps are found, fall back to the default configuration defined in the user's home directory
~/.eslintrc
.eslintignore
File
You can tell ESLint to ignore certain files and directories by creating a .eslintignore
file in the project root directory. .eslintignore
file is a plain text file where each line is a glob pattern indicating which paths should be ignored for detection, something like .gitignore
.
E.g:
# 这是一个注释
node_modules/
dist/*.js
ESLint ignore files can also be reset by parameters on the command line: eslint . --ignore-path .gitignore
, that is, directly use .gitignore as .eslintignore
Prettier
According to the introduction of Prettier's official website, Prettier is an opinionated code formatting tool that supports multiple languages and is integrated into many editors, and has become the preferred solution to all code formatting problems.
Prettier and ESLint do have some overlap when it comes to formatting code, but the big picture is different: ESLint's main job is to check code quality and give hints , it can provide very limited formatting capabilities (ESLint also It is not recommended to use its own formatting function), and only supports JavaScript/TypeScript; while Prettier has greater advantages in formatting code , supporting JavaScript, Flow, TypeScript, CSS, SCSS, Less, JSX, Vue, GraphQL, JSON, Languages such as Markdown.
Prettier command line
npm install prettier -D
# 格式化所有文件
npx prettier --write .
VS Code uses the Prettier plugin
When we submit the code, use the command line to verify the code format, and then go back and change the format line by line. Resubmitting the code is a very inefficient behavior. In addition, if the project is too large and there are many files changed, it may take time to format using Prettier. will also be longer.
VS Code installs the Prettier plugin so that it can format files as they are saved for on-the-fly formatting.
After installing the Prettier plugin, set VS Code's default formatter to Prettier in the user or workspace settings (ie settings.json
).
E.g:
{
// 设置全部语言在保存时自动格式化
"editor.formatOnSave": true,
// 设置全部语言的默认格式化程序为 prettier
"editor.defaultFormatter": "esbenp.prettier-vscode",
// 设置特定语言 JavaScript 的默认格式化程序为 prettier,并设置在保存时自动格式化
"[javascript]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
// prettier 插件配置的公共规则
"prettier.semi": true,
"prettier.arrowParens": "avoid",
"prettier.singleQuote": false,
"prettier.tabWidth": 2,
// vue 文件使用 vetur 作为默认格式化工具
"[vue]": {
"editor.defaultFormatter": "octref.vetur",
"editor.formatOnSave": true
},
// vetur 把格式化 JavaScript 文件交给 prettier 处理
"vetur.format.defaultFormatter.js": "prettier",
"vetur.format.defaultFormatterOptions": {
// vetur 使用的 prettier 的规则,此处的规则比上面设置的公共规则优先级高
"prettier": {
"semi": false,
"singleQuote": true
}
}
}
关于特定语言默认有:javascript
、javascriptreact
、typescript
、typescriptreact
、json
、graphql
. Other languages can be used insettings.json
files.associations
associated file format.
Still the same problem as ESLint, since the Prettier plugin can be used in VS Code to format it in real time, is it possible to use the command line Prettier?
The answer is that the command line Prettier is still needed, because it is not guaranteed that all developers of the project use VS Code, or the Prettier plugin may be manually turned off. In any case, the code submitted to the warehouse must conform to the unified code specification and Coding style, so a Prettier format must be done before submitting to the repository.
Prettier configuration
configuration file
Prettier profiles support several forms:
- 根目录
.prettierrc
文件,YML
、JSON
配置格式,并且支持.yaml
、.yml
,.json
,.js
; - Root directory creates
prettier.config.js
file, and externalexport
an object - Create a new
Prettier
attribute inpackage.json
f8e83e5ba0352066556412c3e16c4ad9---
Attributes
For example to create prettierrc.js
:
module.exports = {
printWidth: 80, //换行的宽度,如果超过会进行换行,默认为80
tabWidth: 2, //tab的空格宽度,默认为80
useTabs: false, //缩进用tab还是空格,默认为false,表示用空格进行缩减
singleQuote: false, //字符串是否使用单引号,JSX会忽略这个配置,默认为false,使用双引号
semi: true, //行尾是否使用分号,默认为true
trailingComma: 'none', //是否使用尾逗号,有三个可选值"<none|es5|all>"
bracketSpacing: true, //对象大括号直接是否有空格,默认为true,效果:{ foo: bar }
arrowParens: 'avoid', //箭头函数的单参数是否用括号包裹,有两个可选值"<always|avoid>"
parser: 'babylon', //代码的解析引擎,默认为babylon,与babel相同。
}
.prettierignore
File
Use the .prettierignore
file to completely ignore (ie not reformat) certain files and folders, just like the .eslintignore
file.
Prettier with ESLint
When ESLint and Prettier are used together, the part of the rules that they have intersection may lead to inconsistent code format after ESLint and Prettier format (such as single and double quotation marks / whether to use semicolons, etc.). For example, if Prettier formats the code and then uses ESLint to detect it, there will be some warnings or errors caused by formatting. After ESLint repairs it, it does not conform to the Prettier format, and then it will be formatted again when saving, and then it will fall into "death". cycle".
The main solution to this problem is to make a fuss on the rule configuration file of ESLint, install a specific extension, configure it at the end of the rule, and realize the coverage of the ESLint rule by the Prettier rule.
This requires the eslint-config-prettier extension mentioned earlier, its role is to disable all those ESLint rules that are not necessary or conflict with prettier.
npm install eslint-config-prettier -D
// 在 .eslintrc.* 文件中的 extends 字段的最后添加 prettier
{
"extends": [
"eslint:recommended", // 已经配置的扩展
"prettier" // prettier 扩展添加到其他扩展的后面,可以实现 Prettier 规则对 ESLint 规则的覆盖
]
}
The above is only to resolve some conflicts between ESLint and Prettier, and realize that running ESLint command will perform relevant verification according to Prettier's rules. However, if you want to format the code, you have to manually run the relevant commands of Prettier to format. The community's solution is to use Prettier instead of ESLint's formatting function when using eslint --fix
.
At this time, you need to use the eslint-plugin-prettier mentioned earlier
npm install eslint-plugin-prettier -D
// 在 .eslintrc.* 中的配置如下
{
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error"
}
}
At this point, execute eslint --fix
actually use Prettier's rules to format the code. Add "prettier/prettier": "error"
rules
in ---84b3a707fdc1dbadda67c9706f945f97---, ESLint will report an error when there is a formatting problem detected by Prettier's rules.
If you want to resolve rule conflicts and automatic formatting at the same time, you can simplify it as follows:
// 在 .eslintrc.* 中的配置如下
{
"extends": ["plugin:prettier/recommended"]
}
The above configuration is equivalent to the following configuration:
{
"extends": ["prettier"], // eslint-config-prettier 提供的,用于覆盖起冲突的规则
"plugins": ["prettier"], // 注册 eslint-plugin-prettier 插件
"rules": {
"prettier/prettier": "error",
"arrow-body-style": "off",
"prefer-arrow-callback": "off"
}
}
Husky + lint-staged
The last two tools in the entire front-end code specification and programming style process will be briefly introduced.
In order to ensure that the code in the warehouse conforms to the code specification and programming style, the best way is to ensure that the local code has passed the check before it can be pushed to the remote, that is, the code check is triggered locally git commit
before the operation. , so you need the githook tool husky
.
# husky 的初始化,创建 .husky/ 目录并制定该目录为 git hooks 所在的目录,并且在 .husky/ 目录下会新增 pre-commit 的 shell 脚本,并且加入了 npm test 命令
npx husky-init && npm install
# 在进行 git commit 之前运行 npx eslint src/** 检查
npx husky add .husky/pre-commit "npx eslint src/**"
However, it is very inefficient to check all files for each submission. It is best to scan only the currently modified files each time, that is, only git add
is added to the stage
cache area. The file is scanned so that only incremental code is checked. Here you need to use the lint-staged
tool to identify the files that are added to the stage
buffer.
// package.json
{
"lint-staged": {
"*.{js}": ["npx eslint --fix"]
}
}
The currently changed .js files are detected and automatically repaired when they are submitted. After the automatic repair is completed, lint-staged will add the changed files to the temporary storage area again by default. If there are errors that cannot be repaired, an error message will be reported.
When used with husky, modify .husky/pre-commit
and run npx lint-staged
before commit to verify the files submitted to the staging area:
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx lint-staged
husky + lint-staged + eslint for simpler integration
use mrm
# mrm最新版本使用 npx 执行有问题,所以使用 2.x 版本
npx mrm@2 lint-staged
It is actually equivalent to a task that does three things:
- Added lint-staged configuration in
package.json
- set
pre-commit
git hook - Install dependencies
Answer the question at the beginning of the article
Who controls whether the indented code style is 2 spaces or 4 spaces? VS Code default settings? Or Prettier?
1. .vscode/settings.json
in "editor.tabSize": 4
, but if you set "editor.detectIndentation": true
, it will be automatically detected according to the content of the opened file, for example, although the set tabSize is 4, When the file is opened, the tabSize of the file content is 2, so 2 will still be used. If it is set to false, the subsequent tabSize will use 4.
{
// 根据打开文件的内容自动检测 #editor.tabSize#和#editor.intertSpaces#
// 例如虽然下面设置的 tabSize 为 4,但是当前文件打开时是文件内容的 tabSize 为 2,所以依然会沿用 2,如果设置为 false,后续的 tabSize 则会使用 4
"editor.detectIndentation": true,
"editor.insertSpaces": true, //是否使用空格
"editor.tabSize": 4 // 空格或者制表符的大小
}
So far, create a new one index.js
the file indentation is 4 spaces
2. The EditorConfig plugin is installed in VS Code, and the .editorconfig
configuration file is created. The indented code style will be controlled by EditorConfig's indent_style
and indent_size
.
[*.{js,jsx,ts,tsx,vue}]
indent_style = space
indent_size = 2
As of now, index.js
the indentation of the file is 2 spaces
3. VS Code installs the Prettier plugin and creates a .prettierrc.js
configuration file. The indented code style will be controlled by Prettier's tabWdith
.
tabWidth: 6
As of now, index.js
the indentation of the file is 6 spaces
Therefore, the indented code style needs to see what plugins are installed. In general, if all three configurations and tools are used, the priority is: Prettier > EditorConfig > VS Code settings.json
Recommended reading
- Notes on using Visual Studio Code
- Project constraints of Vscode you don't know | Warehouse configuration
- Unified code style tool - EditorConfig
- Looking back at the success of ESLint
- ESLint configuration item resolution
- Parse package name of ESLint
- Discussion on the working principle of ESLint
- The implementation principle of Eslint is actually quite simple
- Discussion on the working principle of ESLint
- Zero-based understanding of the core principles of ESLint
- Analysis of the principle of eslint
- Write your own eslint rules that meet your business needs
- Why can Eslint check and fix formatting issues but Babel can't?
- Enable project formatting from ESLint
- Front-end Code Specification Engineering Best Practices - ESLint
- Prettier just read this one
The author got N+1 in the 5th wave of layoffs of an education company, and now I am preparing to apply for a job. If your company has front-end related positions that are recruiting, please contact the author, please indicate your purpose, thank you for reading.
- wx: qiqihaobenben
- emial: chenfangxu_qixin@163.com
- github: https://github.com/qiqihaobenben
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。