如何在Visual Studio代码中使用漂亮的代码格式化代码

本文介绍如何在Visual Studio Code中利用Prettier插件自动格式化代码,包括设置自动格式化、调整配置选项以及创建配置文件以确保团队代码一致性。

介绍 (Introduction)

Formatting code consistently is a challenge, but modern developer tools make it possible to automatically maintain consistency across your team’s codebase.

一致地格式化代码是一个挑战,但是现代的开发人员工具可以自动维护团队代码库的一致性。

In this article, you’ll set up Prettier to automatically format your code in Visual Studio Code, also known as VS Code.

在本文中,您将设置Prettier以在Visual Studio Code(也称为VS Code)中自动设置代码格式。

For demonstration purposes, here’s the sample code you will be formatting:

出于演示目的,这是您将要格式化的示例代码:

const name = "James";

const person ={first: name
}

console.log(person);

const sayHelloLinting = (fName) => {
console.log(`Hello linting, ${fName}`)
}

sayHelloLinting('James');

If you’re familiar with code formatting, you may notice some missteps:

如果您熟悉代码格式,则可能会发现一些错误的步骤:

  • A mix of single and double-quotes.

    单引号和双引号的混合。
  • The first property of the person object should be on its own line.

    person对象的第一个属性应位于其自己的行上。

  • The console statement inside of the function should be indented.

    函数内部的console语句应缩进。
  • You may or may not like the optional parenthesis surrounding the parameter of the arrow function.

    您可能喜欢或可能不喜欢arrow函数参数周围的可选括号。

先决条件 (Prerequisites)

To follow this tutorial, you will need to download and install Visual Studio Code.

要遵循本教程,您将需要下载并安装Visual Studio Code

To work with Prettier in Visual Studio Code, you’ll need to install the extension. To do this, search for Prettier - Code Formatter in the extension panel of VS Code. If you’re installing it for the first time, you’ll see an install button instead of the uninstall button shown here:

要在Visual Studio Code中使用Prettier,您需要安装扩展。 为此,请在VS Code的扩展面板中搜索Prettier - Code Formatter 。 如果是首次安装,则会看到安装按钮,而不是此处显示的卸载按钮:

步骤1 —使用格式文档命令 (Step 1 — Using the Format Document Command)

With the Prettier extension installed, you can now leverage it to format your code. To start, let’s explore using the Format Document command. This command will make your code more consistent with formatted spacing, line wrapping, and quotes.

安装了Prettier扩展程序后,您现在可以利用它来格式化代码了。 首先,让我们探索使用“ 格式文档”命令。 此命令将使您的代码与带格式的空格,换行符和引号更加一致。

To open the command palette, you can use COMMAND + SHIFT + P on macOS or CTRL + SHIFT + P on Windows.

要打开命令选项板,可以在macOS上使用COMMAND + SHIFT + P或在Windows上使用CTRL + SHIFT + P

In the command palette, search for format and then choose Format Document.

在命令面板中,搜索format ,然后选择“设置文档格式”

You may then be prompted to choose which format to use. To do so, click the Configure button:

然后可能会提示您选择要使用的格式。 为此,请单击配置按钮:

Then choose Prettier - Code Formatter.

然后选择“ Prettier-Code Formatter”

Note: If you do not see a prompt for selecting a default format, you can manually change this in your Settings. Set Editor: Default Formatter to ebsenp.prettier-vscode.

注意:如果没有提示您选择默认格式,则可以在“设置”中手动更改此格式。 将编辑器:默认格式设置为ebsenp.prettier-vscode

Your code is now formatted with spacing, line wrapping, and consistent quotes:

现在,您的代码已使用空格,换行符和一致的引号进行了格式化:

const name = 'James';

const person = { first: name };

console.log(person);

const sayHelloLinting = (fname) => {
  console.log(`Hello linting, ${fName}`);
}

sayHelloLinting('James');

This also works on CSS files. You can turn something with inconsistent indentation, braces, new lines, and semicolons into well-formatted code. For example:

这也适用于CSS文件。 您可以将缩进,大括号,换行和分号不一致的内容转换为格式正确的代码。 例如:

body {color: red;
}
h1 {
  color: purple;
font-size: 24px
}

Will be reformatted as:

将重新格式化为:

body {
  color: red;
}
h1 {
  color: purple;
  font-size: 24px;
}

Now that we’ve explored this command, let’s look at how this can me implemented to run automatically.

现在,我们已经研究了该命令,让我们看看如何实现该命令以自动运行。

步骤2 —在保存时格式化代码 (Step 2 — Formatting Code on Save)

So far, you’ve had to manually run a command to format your code. To automate this process, you can choose a setting in VS Code to have your files automatically formatted when you save. This also ensures that code doesn’t get checked to version control that’s not formatted.

到目前为止,您必须手动运行命令来格式化代码。 要自动执行此过程,可以在VS Code中选择一个设置,以在保存时自动格式化文件。 这也可以确保不会将代码检查到未经格式化的版本控制中。

To change this setting, press COMMAND + , on macOS or CTRL + , on Windows to open the Settings menu. Once the menu is open, search for Editor: Format On Save and make sure that option is checked:

要更改此设置,请在macOS上按COMMAND + , CTRL + ,在Windows上按CTRL + ,来打开“ 设置”菜单。 打开菜单后,搜索“ Editor: Format On Save ,并确保选中该选项:

Once this is set, you can write your code as usual and it will be automatically formatted when you save the file.

设置好之后,您可以照常编写代码,并且在保存文件时会自动将其格式化。

步骤3 —更改漂亮的配置设置 (Step 3 — Changing the Prettier Configuration Settings)

Prettier does a lot of things for you by default, but you can also customize the settings.

默认情况下,Prettier会为您做很多事情,但您也可以自定义设置。

Open the Settings menu. Then, search for Prettier. This will bring up all of the settings that you can change:

打开设置菜单。 然后,搜索Prettier 。 这将显示您可以更改的所有设置:

Here are a few of the most common settings:

以下是一些最常见的设置:

  • Single Quote - Choose between single and double-quotes.

    单引号 -在单引号和双引号之间选择。

  • Semi - Choose whether or not to include semicolons at the end of lines.

    -选择是否要包括行的结束分号。

  • Tab Width - Specify how many spaces you want a tab to insert.

    制表符宽度 -指定要插入制表符的空格。

The downside to using the built-in settings menu in VS Code is that it doesn’t ensure consistency across developers on your team.

使用VS Code中的内置设置菜单的不利之处在于,它不能确保团队中开发人员之间的一致性。

步骤4 —创建更漂亮的配置文件 (Step 4 — Creating a Prettier Configuration File)

If you change settings in your VS Code, someone else could have an entirely different configuration on their machine. You can establish consistent formatting across your team by creating a configuration file for your project.

如果您在VS Code中更改设置,则其他人的计算机上可能会有完全不同的配置。 您可以通过为项目创建配置文件来在整个团队中建立一致的格式。

Create a new file called .prettierrc.extension with one of the following extensions:

创建一个名为.prettierrc. extension的新文件.prettierrc. extension .prettierrc. extension带有以下扩展之一:

  • yml

    yml

  • yaml

    yaml

  • json

    json

  • js

    js

  • toml

    toml

Here’s an example of a simple configuration file using JSON:

这是一个使用JSON的简单配置文件的示例:

{
  "trailingComma": "es5",
  "tabWidth": 4,
  "semi": false,
  "singleQuote": true
}

For more specifics on the configuration files, check out the Prettier Docs. After creating one of these and checking it into your project, you can ensure that every team member follows the same formatting rules.

有关配置文件的更多详细信息,请查看Prettier Docs 。 创建其中一个并将其检入到项目后,您可以确保每个团队成员遵循相同的格式设置规则。

结论 (Conclusion)

Having consistent code is a good practice. It is particularly beneficial when working on a project with multiple collaborators. Agreeing upon a set of configurations helps with legibility and understanding of code. More time can be devoted to solving challenging technical problems instead of wrestling over solved problems like code indentation.

拥有一致的代码是一个好习惯。 与多个合作者一起进行项目时,这特别有益。 同意一组配置有助于提高可读性和对代码的理解。 可以将更多的时间投入到解决具有挑战性的技术问题上,而不是花时间解决诸如代码缩进之类的已解决问题。

Prettier ensures consistency in your code formatting and makes the process automatic.

更加漂亮的代码可确保代码格式的一致性并使流程自动化。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-format-code-with-prettier-in-visual-studio-code

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值