Prettier is a code formatting program for prettier

Prettier is a code formatting program for prettier

2022-10-31 0 1,151
Resource Number 47221 Last Updated 2025-02-21
¥ 0USD Upgrade VIP
Download Now Matters needing attention
Can't download? Please contact customer service to submit a link error!
Value-added Service: Installation Guide Environment Configuration Secondary Development Template Modification Source Code Installation

The recommended Prettier is an opinionated code formatter. It performs a consistent style by parsing your code and reprinting it with its own rules that account for maximum line length and wrap the code when necessary.

What is an Prettier?

Prettier is an opinionated code formatter that supports:

  • JavaScript (including experimental features)
  • JSX
  • Angular
  • Vue
  • Flow
  • TypeScript
  • CSS, Less, and SCSS
  • HTML
  • Ember/Handlebars
  • JSON
  • GraphQL
  • Markdown, including GFM and MDX
  • YAML

Prettier takes your code by considering the line length and reprints it from scratch.

For example, use the following code:

foo(arg1, arg2, arg3, arg4); 

It fits one line, so it will stay as is. But, we’ve all been there:

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

All of a sudden, the format in which we called the function before broke down because it was too long. Prettier does the job for you:

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

Prettier enforces a consistent code style throughout the code base (that is, does not affect the code format of the AST) because it ignores the original style * by parsing it and reprinting the parsed AST using its own rules, which use maximum lines to take into account, Wrap the code if necessary.

Basic Principles

< Correctness

The first requirement of an Prettier is to output valid code that behaves exactly as it does before formatting. Report any code on Prettier that does not follow the correctness rules of an Prettier — it’s a bug that needs fixing!

String

Double quotes or single quotes? Prettier Choose the one with the fewest escapes on the prettier. It’s gettin’ better!” Not ‘It\’s gettin\’ better! ‘. If a tie or string does not contain any quotes, an Prettier uses double quotes by default (but this can be changed using the singleQuote option).

JSX has its own quote option: jsxSingleQuote. JSX is derived from HTML, where the primary use of attribute quotes is double quotes. Browser development tools follow this convention by always displaying HTML in double quotes, even if the source code uses single quotes. A separate option allows single quotes for JS and double quotes for “HTML” (JSX).

Blank line
It turns out that empty lines are difficult to generate automatically. Prettier takes the approach of keeping empty lines in the original source code. There are two additional rules:

    • Prettier folds empty lines into one empty line.

The blank lines at the beginning and end of the

  • block (and the entire file) are removed. (Files always end with a newline character, though.)

Multi-line object

By default, the printing algorithm of an Prettier prints expressions on a single line where appropriate. However, objects are used for many different things in JavaScript, and sometimes it does help with readability if they stay multiple lines. See, for example, object lists, nested configurations, style Sheets, and keying methods. We can’t find a good rule for all of these cases, so if there is a newline between the first key and the first key in {the original source code, an Prettier keeps objects multiple lines. The result is that long single-line objects are automatically expanded, but short multi-line objects are never collapsed.
Tip: If you have a multi-line object, you want to merge it into one line:

const user =  {
name: "John Doe",
age: 30,
}; 

All you need to do is remove the newline {:

after the following

const user = {  name: "John Doe",
  age: 30
};

Then run Prettier:

const user  = { name: "John Doe", age: 30 }; 

If you want to use multiple lines again, add a newline after {:

const user  = {
name: "John Doe", age: 30 }; 

Then run Prettier:

const user =  {
name: "John Doe",
age: 30,
}; 

JSX

When JSX is involved, Prettier prints slightly differently than other JS on Prettier:

function  greet(user) {
return user
? `Welcome back, ${user.name}! `
: "Greetings, traveler!  Sign up today!" ;
}

function Greet({ user }) {
return (
< div> 
{user ?  (
< p> Welcome back, {user.name}! < /p> 
) : (
< p> Greetings, traveler!  Sign up today! < /p> 
)}
< /div> 
);
}

First, many people have wrapped their JSX in parentheses, especially in return statements. Prettier follows this common style.

Second, the alternate format makes editing JSX easier. It’s easy to leave a semicolon. Unlike regular JS, the remaining semicolons in JSX will eventually appear on your page as plain text.

<div>
  <p>Greetings, traveler! Sign up today!</p>; {/* <-- Oops! */}
</div>

< Note

When it comes to the content of comments , Prettier really doesn’t prettier. Comments can contain everything from prose to commented out code and ASCII diagrams. Because they can contain anything, Prettier does not know how to format or wrap them. So they stay the same. The only exception to an Prettier is Jsdoc-style comments (block comments * starting with a), whose indentation is fixed on an Prettier.

Then there is the question of where to place the comment in . This proved to be a very difficult problem. Prettier does its best to keep your comments roughly where they are, but that’s not easy because comments can be placed almost anywhere on Prettier.

In general, you get the best results when you place the comment on its own line rather than at the end of the line. Prefer // eslint-disable-next-line.// eslint-disable-line

Note that because an Prettier splits an expression into lines, it is sometimes necessary to move magic notes manually, such as eslint-disable-next-lineand. $FlowFixMe

 Imagine this code:
// eslint-disable-next-line no-eval
const result = safeToEval ?  eval(input) : fallback(input); 

Then you need to add another condition:

// eslint-disable-next-line no-eval
const result = safeToEval & &  settings.allowNativeEval ?  eval(input) : fallback(input); 

Prettier changes to

// eslint-disable-next-line no-eval
const result =
safeToEval & &  settings.allowNativeEval ?  eval(input) : fallback(input); 

This means that the eslint-disable-next-line comment is no longer valid. In this case, you need to move the comment:

const result =
// eslint-disable-next-line no-eval
safeToEval & &  settings.allowNativeEval ?  eval(input) : fallback(input); 

If possible, prefer comments that operate at the line range (for example, eslint-disableand eslint-enable) or at the statement level (for example, /* istanbul ignore next */), which are even safer. Can be used to disable the use of eslint-disable-line and eslint-disable-next-line comments
eslint-plugin-eslint-comments.

Installing Prettier

First, install Prettier locally:

npm install --save-dev --save-exact prettier

Then create an empty configuration file to let the editor and other tools know that you are using Prettier:

echo {}>  .prettierrc.json

Next, create a.PrettierIgnore file to let the Prettier CLI and the editor know which files cannot be formatted . Here’s an example:

# Ignore artifacts:
build
coverage

Now format all files using Prettier:

npx prettier --write .

prettier –write . Great for formatting everything, but for large projects it can take a little time. You can run prettier –write app/ format a directory prettier, or Prettier –write app/components/Button.js to format a file Prettier. Or format all the tests in the directory using glob likeprettier –write “app/**/*.test.js” (see fast-glob for supported glob syntax).

If you have a CI setting, run the following command in it to make sure everyone runs Prettier. This avoids merge conflicts and other collaboration issues!

npx prettier --check .

–check is like –write, but only checks if files have been formatted, rather than overwriting them. prettier –write prettier –check is the most common way to run Prettier.

Integration with Linter

Linter usually contains not only code quality rules, but also style rules. Most style rules are not necessary when using Prettier, but even worse, they may conflict with Prettier! Using Prettier for code formatting and using linter for code quality, as described in Prettier vs. Linters.

When you search Prettier and your linter on the Internet, you may find more entries on Prettier. These are not generally recommended, but may be useful in some situations.

First of all, we have plugins that let you run Prettier like a linter rule:

  • eslint Prettier
  • stylelint-prettier

These add-ons are especially useful when Prettier is new. By running Prettier in your linter, you don’t have to set up any new infrastructure. You can reuse your editor integration for linter. But now you can run prettier –check. And most editors have Prettier support.

The disadvantages of these plugins are:

  • You’ll end up with a lot of red wavy lines in your editor, which is annoying. Prettier is supposed to make you forget about formatting – not face it!
  • They are slower than running Prettier.
  • They are still the indirect layers through which things can break down.

—END—

Open Source license: MIT license

资源下载此资源为免费资源立即下载
Telegram:@John_Software

Disclaimer: This article is published by a third party and represents the views of the author only and has nothing to do with this website. This site does not make any guarantee or commitment to the authenticity, completeness and timeliness of this article and all or part of its content, please readers for reference only, and please verify the relevant content. The publication or republication of articles by this website for the purpose of conveying more information does not mean that it endorses its views or confirms its description, nor does it mean that this website is responsible for its authenticity.

Ictcoder Free source code Prettier is a code formatting program for prettier https://ictcoder.com/kyym/prettier-is-a-code-formatting-program-for-prettier.html

Share free open-source source code

Q&A
  • 1, automatic: after taking the photo, click the (download) link to download; 2. Manual: After taking the photo, contact the seller to issue it or contact the official to find the developer to ship.
View details
  • 1, the default transaction cycle of the source code: manual delivery of goods for 1-3 days, and the user payment amount will enter the platform guarantee until the completion of the transaction or 3-7 days can be issued, in case of disputes indefinitely extend the collection amount until the dispute is resolved or refunded!
View details
  • 1. Heptalon will permanently archive the process of trading between the two parties and the snapshots of the traded goods to ensure that the transaction is true, effective and safe! 2, Seven PAWS can not guarantee such as "permanent package update", "permanent technical support" and other similar transactions after the merchant commitment, please identify the buyer; 3, in the source code at the same time there is a website demonstration and picture demonstration, and the site is inconsistent with the diagram, the default according to the diagram as the dispute evaluation basis (except for special statements or agreement); 4, in the absence of "no legitimate basis for refund", the commodity written "once sold, no support for refund" and other similar statements, shall be deemed invalid; 5, before the shooting, the transaction content agreed by the two parties on QQ can also be the basis for dispute judgment (agreement and description of the conflict, the agreement shall prevail); 6, because the chat record can be used as the basis for dispute judgment, so when the two sides contact, only communicate with the other party on the QQ and mobile phone number left on the systemhere, in case the other party does not recognize self-commitment. 7, although the probability of disputes is very small, but be sure to retain such important information as chat records, mobile phone messages, etc., in case of disputes, it is convenient for seven PAWS to intervene in rapid processing.
View details
  • 1. As a third-party intermediary platform, Qichou protects the security of the transaction and the rights and interests of both buyers and sellers according to the transaction contract (commodity description, content agreed before the transaction); 2, non-platform online trading projects, any consequences have nothing to do with mutual site; No matter the seller for any reason to require offline transactions, please contact the management report.
View details

Related Article

make a comment
No comments available at the moment
Official customer service team

To solve your worries - 24 hours online professional service