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