diff --git a/docs/rationale.md b/docs/rationale.md index 08b9f302..8953de4d 100644 --- a/docs/rationale.md +++ b/docs/rationale.md @@ -35,6 +35,107 @@ By default, Prettier’s printing algorithm prints expressions on a single line [stylesheets]: https://github.com/prettier/prettier/issues/74#issuecomment-275262094 [keyed methods]: https://github.com/prettier/prettier/pull/495#issuecomment-275745434 +### Semicolons + +This is about using the `--no-semi` option. + +Consider this piece of code: + + +```js +if (shouldAddLines) { + [-1, 1].forEach(delta => addLine(delta * 20)) +} +``` + +While the above code works just fine without semicolons, Prettier actually turns it into: + + +```js +if (shouldAddLines) { + ;[-1, 1].forEach(delta => addLine(delta * 20)) +} +``` + +This is to help you avoid mistakes. Imagine adding this line: + +```diff + if (shouldAddLines) { ++ console.log('Do we even get here??') + [-1, 1].forEach(delta => addLine(delta * 20)) + } +``` + +Oops! The above actually means: + + +```js +if (shouldAddLines) { + console.log('Do we even get here??')[-1, 1].forEach(delta => addLine(delta * 20)) +} +``` + +With a semicolon in front of that `[` such issues never happen. It makes the line independent of other lines so you can move and add lines without having to think about ASI rules. + +This practice is also common in [standard] which uses a semicolon-free style. + +[standard]: https://standardjs.com/rules.html#semicolons + +### Imports + +Prettier can break long `import` statements across several lines: + +```js +import { + CollectionDashboard, + DashboardPlaceholder +} from "../components/collections/collection-dashboard/main"; +``` + +The following example doesn't fit within the print width, but Prettier prints it in a single line anyway: + +```js +import { CollectionDashboard } from "../components/collections/collection-dashboard/main"; +``` + +This might be unexpected by some, but we do it this way since it was a common request to keep `import`s with single elements in a single line. The same applies for `require` calls. + +### JSX + +Prettier prints things a little differently compared to other JS when JSX is involved: + +```jsx +function greet(user) { + return user + ? `Welcome back, ${user.name}!` + : "Greetings, traveler! Sign up today!"; +} + +function Greet({ user }) { + return ( +
Welcome back, {user.name}!
+ ) : ( +Greetings, traveler! Sign up today!
+ )} +Greetings, traveler! Sign up today!
; {/* <-- Oops! */} +