search
HomeDevelopment ToolsVSCodeTake you to use the Format function of VSCode to implement code formatting

Just use the Format function that comes with VSCode to meet configurable code formatting needs! The following article will introduce you to the Format function of VSCode. I hope it will be helpful to you!

Take you to use the Format function of VSCode to implement code formatting

#In recent years, the development environment has paid more and more attention to the standardization of code. Using tools to check and automatically repair has become the first choice for code assurance.

Generally use auxiliary tools such as Lint (ESLint StyleLint) or Prettier. Through simple configuration and deployment, you can use some popular Code Style specifications to achieve The purpose of automatic prompting, automatic repair, automatic execution and supervision.

But I don’t know if you have encountered the following situations:

  • When typing code in the IDE, because there is no real-time format (usually automatically formatted when saving), A red prompt always appears, and I always think that my grammar is wrong, but in fact it is just that it has not been formatted. (For example, the automatic verification prompt of the ESLint plug-in)

  • When I first started using it, I always encountered rules that I didn’t understand (maybe too strict), and I had to click into the prompt to view it. The specific reason is that it is equivalent to learning the rules while developing.

  • I wrote a piece of code. After saving, the code suddenly became longer and all lines were wrapped. The 50 lines of code were suddenly stretched to 100 lines. I won’t name anyone here.

  • There are not many requirements for code specifications (more referring to formatting). For example, the project is relatively small, the project schedule is relatively tight, etc. As long as it meets the basic formatting requirements.

Especially the last one. In fact, many small projects only need to meet the most basic formatting, which can ensure that the team can meet and implement a set of simple specifications. Other comparisons Strict regulations can be ignored.

A concept is mentioned here. There are two types of specifications: Formatting rules and Code quality rules (Code-quality rules) . The basic specifications mentioned above basically belong to code format rules.

The following are the commonly used and basic formatting rules, that is, code format rules, taking standardjs style as an example:

As you can see, they are basically semicolons Enter space space related specifications, and these specifications have been integrated in some IDEs.

For example, VSCode can satisfy all the above rules through simple configuration.

VSCode Format

VSCode itself has a Format function, which is supported by most file types. The default shortcut key is Ctrl K D.

Take you to use the Format function of VSCode to implement code formatting

also supports setting to Format on Save.

Take you to use the Format function of VSCode to implement code formatting

#Then list out which of the above basic specifications are not included in the default Format function.

  • semicolon. - There is no specification by default and can be configured through settings.

  • Space indent . - The default TabSize is 4 spaces, which can be configured through settings.

  • When declaring a function, add a space between the brackets and the function name. - Unlike standardjs, VSCode has no spaces by default.

  • Leave a blank line at the end of the file. - None by default, can be configured through settings.

There are only 4 of them. The third one can be said to have different rules, but there are rules, so there are 3 in total. Therefore, most rules are already supported by the default format function.

1. Semicolon

is divided into three specifications: it is required that must have a semicolon ; prohibits semicolon; is OK. There are various popular specifications on the market, but they generally require that must contain or prohibits .

VSCode has no requirements by default, but it can be defined through settings:

Take you to use the Format function of VSCode to implement code formatting

  • ignore By default, it can be used with or without a semicolon;

  • insert A semicolon is required;

  • remove disallows semicolons.

2. Indentation specifications

are generally divided into two specifications, 2 spaces or 4 spaces. Most of them are popular on the market now. In the specification, 2 spaces prevail.

The default specification of VSCode is:

  • Detect Indentation Corresponding settings: editor.detectIndentation Default value true, based on the current file content, detect whether the current file has 2 spaces or 4 spaces space, and then Format according to this;
  • Tab Size corresponds to settings: editor.tabSize: default value 4, if it is a new file , it is determined based on this value. The default is 4 tab size.

Take you to use the Format function of VSCode to implement code formatting

The above picture is the default configuration. If you want all files to be indented with 2 spaces as the norm, you can turn off Detect Indentation first. , and then set Tab Size to 2.

If you do not turn off Detect Indentation and only change Tab Size to 2, the indentation will be based on the file content, and then the new file will be indented by 2 spaces.

VSCode detects the tabsize of the file based on what it is. You can see it in the status bar at the bottom of the file and click it to change it.

Take you to use the Format function of VSCode to implement code formatting

3. Leave a blank line at the end of the file

Search for the keyword insertFinalNewline in settings, the default option is Disabled, when checked, a blank line will be left at the end of all files when saving.

Take you to use the Format function of VSCode to implement code formatting

To sum up

To sum up, all settings are configured as follows:

It is recommended to set settings under Workspace. After setting, the settings.json file will be generated under the .vscode path and can be submitted. Unify the internal specifications of the development team on git.

// .vscode/settings.json
{
  "editor.formatOnSave": true, // 保存文件自动format
  "javascript.format.semicolons": "insert", // js文件,强制必须有分号,设置`remove`则禁止分号
  "typescript.format.semicolons": "insert", // ts文件,同上
  "editor.tabSize": 2, // 设置默认缩进为2个空格
  "editor.detectIndentation": false, // 是否强制所有文件按tabSize设置缩进;"否"则根据文件内容缩进、新建文件按tabSize缩进。
  "files.insertFinalNewline": true, // 所有文件末尾留一空行
  "[javascript]": {
    "editor.defaultFormatter": "vscode.typescript-language-features" // 设置js类型文件的默认format为VSCode自带Format
  },
  "[javascriptreact]": {
    "editor.defaultFormatter": "vscode.typescript-language-features" // jsx文件,同上
  },
  "[css]": {
    "editor.defaultFormatter": "vscode.css-language-features" // css文件,同上
  },
  "[less]": {
    "editor.defaultFormatter": "vscode.css-language-features" // less文件,同上
  }
}

In fact, more format configurations can be configured in VSCode settings, you can explore by yourself.

Other format files Format

For example, css, less, json, md, etc. I personally feel that it is enough to just use VSCode’s default one.

Other specifications:

In addition to the code format rules mentioned above, other specifications are code quality rules Yes, this can be done with the ESLint specifications, because these specifications do not conflict with the above code format rules, and with the auto fix on save of ESLint, When you can save the file, first use VSCode format code format rules, and then use ESLintprocessingcode quality rules. To give a few examples:

  • enforces single quotation marks or double quotation marks . eslint: quotes

  • is always used. === replaces ==. eslint: eqeqeq

For the usage of ESLint, you can refer to the previous article: ESLint with VSCode Unify team front-end code specifications

Finally

This article summarizes how to standardize the front-end Codecode format specifications## using only VSCode development tools #, and supports configurable and automatic file formatting code functions.

Advantages:

  • #Simple configuration, no need to install various npm or plug-ins, VSCode has its own functions.

  • Suitable for small, simple projects, or projects with low demand for

    code format specifications, suitable for small factories.

  • Some rules support customization and can be configured according to actual needs.

Disadvantages:

  • There are not many rules, basically

    code format rules, do Without code quality rules verification, it needs to be combined with ESLint.

  • It cannot meet the requirements of projects with relatively high format specifications, such as large projects and large factories.

  • Compared with

    ESLint, there are few rules and not much configurability.

  • Compared with

    Prettier, there are very few rules, certainly not as good as some popular coding style specifications.

  • There is no way to automatically verify the code when submitting it through Git Hooks.

This article only provides a code format specification solution and an idea. Whether it is suitable for you depends on your own needs. .

For more knowledge about VSCode, please visit: vscode Basic Tutorial!

The above is the detailed content of Take you to use the Format function of VSCode to implement code formatting. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Visual Studio: Exploring the Free and Paid OfferingsVisual Studio: Exploring the Free and Paid OfferingsApr 22, 2025 am 12:09 AM

The main difference between the free and paid versions of VisualStudio is the richness of features and the service supported. The free version (Community) is suitable for individual developers and small teams, providing basic development tools; the paid version (Professional and Enterprise) provides advanced features such as advanced debugging and team collaboration tools, suitable for large projects and enterprise-level development.

Visual Studio Community Edition: The Free Option ExplainedVisual Studio Community Edition: The Free Option ExplainedApr 21, 2025 am 12:09 AM

VisualStudioCommunityEdition is a free IDE suitable for individual developers, small teams and educational institutions. 1) It provides functions such as code editing, debugging, testing and version control. 2) Based on the Roslyn compiler platform, it supports multiple programming languages ​​and integrates Git and TFVC. 3) Advanced features include unit testing, optimization suggestions include turning off unnecessary extensions and using a lightweight editor.

Visual Studio: Building Applications with EaseVisual Studio: Building Applications with EaseApr 20, 2025 am 12:09 AM

VisualStudio is an integrated development environment (IDE) developed by Microsoft, which supports a variety of programming languages, including C#, C, Python, etc. 1. It provides IntelliSense function to help write code quickly. 2. The debugger allows setting breakpoints, step-by-step code execution, and identifying problems. 3. For beginners, creating a simple console application is a great way to get started. 4. Advanced usage includes the application of design patterns such as project management and dependency injection. 5. Common errors can be solved step by step through debugging tools. 6. Performance optimization and best practices include code optimization, version control, code quality inspection and automated testing.

Visual Studio and VS Code: Understanding Their Key DifferencesVisual Studio and VS Code: Understanding Their Key DifferencesApr 19, 2025 am 12:16 AM

VisualStudio is suitable for large-scale projects and enterprise-level application development, while VSCode is suitable for rapid development and multilingual support. 1. VisualStudio provides a comprehensive IDE environment and supports Microsoft technology stack. 2.VSCode is a lightweight editor that emphasizes flexibility and scalability, and supports cross-platform.

Is Visual Studio Still Free? Understanding the AvailabilityIs Visual Studio Still Free? Understanding the AvailabilityApr 18, 2025 am 12:05 AM

Yes, some versions of VisualStudio are free. Specifically, VisualStudioCommunityEdition is free for individual developers, open source projects, academic research, and small organizations. However, there are also paid versions such as VisualStudioProfessional and Enterprise, suitable for large teams and enterprises, providing additional features.

Using Visual Studio: Developing Software Across PlatformsUsing Visual Studio: Developing Software Across PlatformsApr 17, 2025 am 12:13 AM

Cross-platform development with VisualStudio is feasible, and by supporting frameworks like .NETCore and Xamarin, developers can write code at once and run on multiple operating systems. 1) Create .NETCore projects and use their cross-platform capabilities, 2) Use Xamarin for mobile application development, 3) Use asynchronous programming and code reuse to optimize performance to ensure efficient operation and maintainability of applications.

How to format json with vscodeHow to format json with vscodeApr 16, 2025 am 07:54 AM

The ways to format JSON in VS Code are: 1. Use shortcut keys (Windows/Linux: Ctrl Shift I; macOS: Cmd Shift I); 2. Go through the menu ("Edit" > "Format Document"); 3. Install JSON formatter extensions (such as Prettier); 4. Format manually (use shortcut keys to indent/extract blocks or add braces and semicolons); 5. Use external tools (such as JSONLint and JSON Formatter).

How to compile vscodeHow to compile vscodeApr 16, 2025 am 07:51 AM

Compiling code in VSCode is divided into 5 steps: Install the C extension; create the "main.cpp" file in the project folder; configure the compiler (such as MinGW); compile the code with the shortcut key ("Ctrl Shift B") or the "Build" button; run the compiled program with the shortcut key ("F5") or the "Run" button.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment