Use Prettier To Format JavaScript code

Source: Internet
Author: User

Use Prettier To Format JavaScript code

If you have programming experience, you should be very clear, it is difficult to make the code concise and clear, and make different code writing styles consistent in a project. Even if you have spent a lot of time to achieve this goal, other developers will also submit their modifications or disable some of the logos to help them quickly submit code, so that your efforts will be at a loss.

It is boring to waste time formatting code. The goal of Prettier is to solve this problem. It will use simple settings to help you overcome the troubles caused by formatting.

What can Prettier do?

Prettier is a special code formatting tool that can automate the formatting process of the entire code library. Therefore, after setting Prettier, you no longer need to discuss code formatting rules, semicolons, line breaks, and other issues with your colleagues. It will import all your code, delete all formats, and reformat the code according to its style rules.

In the Prettier environment, all javascript code is converted into an abstract syntax tree and then formatted again. Therefore, it ensures that no damage changes are made to the written code. For you, everything is magically formatted, and you don't have to worry about it.

For example:

Foo (reallyLongArg (), omgSoManyParameters (), IShouldRefactorThis (), isThereSeriouslyAnotherOne ());

Will be formatted

Foo (
ReallyLongArg (),
OmgSoManyParameters (),
IShouldRefactorThis (),
IsThereSeriouslyAnotherOne ()
);

If you want to try it out, you can try playground. Summary:

Differences with ESLint

This is one of the most common questions. The concise answer is that ESLint is just a code quality tool (ensure there are no unused variables, no global variables, and so on ). Prettier only cares about formatting files (maximum length, mixed labels, spaces, and reference styles ). You can combine ESLint and Prettier to achieve a win-win combination.

Functions of Editorconfig

Prettier 1.9 reads configuration values from editorconfig. Recommended configuration options include indent_style, indent_size/tab_width, and max_line_length.

How to Set

As described above, the Prettier Automation program will format the entire code library. You can use Prettier in the following scenarios:

  • Editor plug-in
  • CLI
  • Pre-commit hooks
Use in the editor

Go to the interaction page of the website, download the corresponding plug-in, and install it in your IDE/Editor. This should be a very simple process. For Visual Studio Code, you only need to download it from the marketplace. Then, a preference ("editor. formatOnSave": true) is added to the user settings ). In this way, it will take effect. I also set "prettier. singleQuote": true based on my needs. Other editor attributes can also be set here.

Use in projects

Install Prettier CLI first. We will add it as the dev dependency, (yarn add prettier -- dev -- exact or npm install -- save-dev -- save-exact prettier ). Prettier recommends installing the appropriate version in the project because Prettier will introduce code format changes when patches are released. After the installation is successful, you only need to run the command yarn prettier -- write index. js for a specific file to generate the index. js file in the current directory.

You can configure other Prettier options as needed, usually using the configuration file. You can also add these to the. prettierrc file and place them in the root folder of the project. Available options can be found on the website.

Then, you can add this command to your NPM script and pass the src folder to it as a glob instead of a separate file. The formatting script is like this: prettier -- write'./src/**/*. {ts, js, css, json }'.

If you do not use this complex configuration, it does not use the. prettierrc file. You can also use the command line parameter to specify the option configuration.

Then you can call it as part of the build step. All changes will also take effect.

In the project, you can further integrate the Prettier code into a pre-commit hook. Install husky in combination with lint-stage/pretty-quick (if you are using other tools, such as ESLint, use lint-stage ). After NPM installs these packages as dev dependencies, you can add the following configurations to the package. json file:

Pretty-quick:

"Scripts ":{
"Precommit": "pretty-quick -- staged"
} Lint-staged:

"Scripts ":{
"Precommit": "lint-staged ",
"Lint-staged ":{
"*. {Ts, js, css, json }":[
"Prettier -- write ",
"Git add"
]
}
}

Note that when you run prettier as a pre-commit hook, it will destroy the status of your project. A solution (recommended by gocarsno on Reddit) stores all unloaded changes (git stash-k) before committing ).

You can add another check in the building step of the project. Facebook did this. I knew it in an employee meeting speech. You can run Prettier on the CI/CD server of the file. If the file output of Prettier is different from the file that is checked in, the server compilation will fail. You can choose to do this, depending on the degree to which you depend.

What are you waiting? Configure Prettier! Do not manually format the project code and ask the machine to do it for you.

I share this article to help more people discover the charm of Prettier.

Using Prettier to format your JavaScript code

This article permanently updates link: https://www.bkjia.com/Linux/2018-03/151124.htm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.