feat(website): enable docs versioning (#5676)

master
Ika 2018-12-25 08:20:35 +08:00 committed by GitHub
parent 439b1649ff
commit f744a84858
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
27 changed files with 3523 additions and 107 deletions

View File

@ -22,9 +22,12 @@ shell.mkdir("-p", docs);
if (isPullRequest) {
// --- Build prettier for PR ---
const pkg = require("../package.json");
pkg.version = `999.999.999-pr.${process.env.REVIEW_ID}`;
pipe(JSON.stringify(pkg, null, 2)).to("package.json");
const newPkg = Object.assign({}, pkg, {
version: `999.999.999-pr.${process.env.REVIEW_ID}`
});
pipe(JSON.stringify(newPkg, null, 2)).to("package.json");
shell.exec("yarn build");
pipe(JSON.stringify(pkg, null, 2)).to("package.json"); // restore
}
shell.exec(`cp ${prettierPath}/standalone.js ${docs}/`);
shell.exec(`cp ${prettierPath}/parser-*.js ${docs}/`);

View File

@ -23,7 +23,7 @@
"babel-preset-env": "1.6.1",
"babel-preset-react": "6.24.1",
"concurrently": "3.5.1",
"docusaurus": "1.3.1",
"docusaurus": "1.6.2",
"js-yaml": "3.10.0",
"svgo": "1.0.4",
"webpack": "4.5.0",

101
website/pages/en/versions.js Executable file
View File

@ -0,0 +1,101 @@
"use strict";
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require("react");
const CompLibrary = require("../../core/CompLibrary");
const Container = CompLibrary.Container;
const CWD = process.cwd();
const versions = require(`${CWD}/versions.json`);
const rootPackageJson = require(`${CWD}/../package.json`);
const masterVersion = rootPackageJson.version;
const isMasterDevVersion = masterVersion.endsWith("-dev");
const devVersion = isMasterDevVersion ? masterVersion : null;
const latestVersion = isMasterDevVersion
? rootPackageJson.devDependencies.prettier
: masterVersion;
const latestDocsVersion = versions[0];
const pastDocsVersions = versions.slice(1);
function Versions(props) {
const { config: siteConfig } = props;
return (
<div className="docMainWrapper wrapper">
<Container className="mainContainer versionsContainer">
<div className="post">
<header className="postHeader">
<h1>{siteConfig.title} Versions</h1>
</header>
<table className="versions">
<tbody>
<tr>
<th>Version</th>
<th>Install with</th>
<th>Documentation</th>
</tr>
<tr>
<td>{latestVersion}</td>
<td>
<code>npm install prettier</code>
</td>
<td>
<a href={`${siteConfig.baseUrl}docs/en/index.html`}>
{latestDocsVersion}
</a>{" "}
(latest)
</td>
</tr>
<tr>
<td>{devVersion}</td>
<td>
<code>npm install prettier/prettier</code>
</td>
<td>
<a href={`${siteConfig.baseUrl}docs/en/next/index.html`}>
next
</a>{" "}
(master)
</td>
</tr>
{pastDocsVersions.length !== 0 &&
pastDocsVersions.map((pastDocsVersion, index) => {
const pastMajorVersion = pastDocsVersion.replace(/^v/, "");
return (
<tr key={index}>
<td>{pastMajorVersion}.x</td>
<td>
<code>
npm install prettier@
{pastMajorVersion}
</code>
</td>
<td>
<a
href={`${
siteConfig.baseUrl
}docs/en/${pastDocsVersion}/index.html`}
>
{pastDocsVersion}
</a>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</Container>
</div>
);
}
module.exports = Versions;

View File

@ -0,0 +1,143 @@
---
id: version-stable-api
title: API
original_id: api
---
```js
const prettier = require("prettier");
```
## `prettier.format(source [, options])`
`format` is used to format text using Prettier. [Options](options.md) may be provided to override the defaults.
```js
prettier.format("foo ( );", { semi: false, parser: "babylon" });
// -> "foo()"
```
## `prettier.check(source [, options])`
`check` checks to see if the file has been formatted with Prettier given those options and returns a `Boolean`. This is similar to the `--list-different` parameter in the CLI and is useful for running Prettier in CI scenarios.
## `prettier.formatWithCursor(source [, options])`
`formatWithCursor` both formats the code, and translates a cursor position from unformatted code to formatted code. This is useful for editor integrations, to prevent the cursor from moving when code is formatted.
The `cursorOffset` option should be provided, to specify where the cursor is. This option cannot be used with `rangeStart` and `rangeEnd`.
```js
prettier.formatWithCursor(" 1", { cursorOffset: 2, parser: "babylon" });
// -> { formatted: '1;\n', cursorOffset: 1 }
```
## `prettier.resolveConfig(filePath [, options])`
`resolveConfig` can be used to resolve configuration for a given source file, passing its path as the first argument. The config search will start at the file path and continue to search up the directory (you can use `process.cwd()` to start searching from the current directory). Or you can pass directly the path of the config file as `options.config` if you don't wish to search for it. A promise is returned which will resolve to:
- An options object, providing a [config file](configuration.md) was found.
- `null`, if no file was found.
The promise will be rejected if there was an error parsing the configuration file.
If `options.useCache` is `false`, all caching will be bypassed.
```js
const text = fs.readFileSync(filePath, "utf8");
prettier.resolveConfig(filePath).then(options => {
const formatted = prettier.format(text, options);
});
```
If `options.editorconfig` is `true` and an [`.editorconfig` file](http://editorconfig.org/) is in your project, Prettier will parse it and convert its properties to the corresponding prettier configuration. This configuration will be overridden by `.prettierrc`, etc. Currently, the following EditorConfig properties are supported:
- `end_of_line`
- `indent_style`
- `indent_size`/`tab_width`
- `max_line_length`
Use `prettier.resolveConfig.sync(filePath [, options])` if you'd like to use sync version.
## `prettier.resolveConfigFile(filePath [, options])`
`resolveConfigFile` can be used to find the path of the Prettier's configuration file will be used when resolving the config (i.e. when calling `resolveConfig`). A promise is returned which will resolve to:
- The path of the configuration file.
- `null`, if no file was found.
The promise will be rejected if there was an error parsing the configuration file.
If `options.useCache` is `false`, all caching will be bypassed.
## `prettier.clearConfigCache()`
As you repeatedly call `resolveConfig`, the file system structure will be cached for performance. This function will clear the cache. Generally this is only needed for editor integrations that know that the file system has changed since the last format took place.
## `prettier.getFileInfo(filePath [, options])`
`getFileInfo` can be used by editor extensions to decide if a particular file needs to be formatted. This method returns a promise, which resolves to an object with the following properties:
```typescript
{
ignored: boolean,
inferredParser: string | null,
}
```
Setting `options.ignorePath` (`string`) and `options.withNodeModules` (`boolean`) influence the value of `ignored` (`false` by default).
Providing [plugin](./plugins.md) paths in `options.plugins` (`string[]`) helps extract `inferredParser` for files that are not supported by Prettier core.
Use `prettier.getFileInfo.sync(filePath [, options])` if you'd like to use sync version.
## `prettier.getSupportInfo([version])`
Returns an object representing the parsers, languages and file types Prettier supports.
If `version` is provided (e.g. `"1.5.0"`), information for that version will be returned, otherwise information for the current version will be returned.
The support information looks like this:
```typescript
{
languages: Array<{
name: string,
since?: string,
parsers: string[],
group?: string,
tmScope?: string,
aceMode?: string,
codemirrorMode?: string,
codemirrorMimeType?: string,
aliases?: string[],
extensions?: string[],
filenames?: string[],
linguistLanguageId?: number,
vscodeLanguageIds?: string[],
}>
}
```
## Custom Parser API
If you need to make modifications to the AST (such as codemods), or you want to provide an alternate parser, you can do so by setting the `parser` option to a function. The function signature of the parser function is:
```js
(text: string, parsers: object, options: object) => AST;
```
Prettier's built-in parsers are exposed as properties on the `parsers` argument.
```js
prettier.format("lodash ( )", {
parser(text, { babylon }) {
const ast = babylon(text);
ast.program.body[0].expression.callee.name = "_";
return ast;
}
});
// -> "_();\n"
```
The `--parser` CLI option may be a path to a node.js module exporting a parse function.

View File

@ -0,0 +1,55 @@
---
id: version-stable-browser
title: Browser
original_id: browser
---
Run Prettier in the browser with the `standalone.js` UMD bundle shipped in the NPM package (starting in version 1.13). The new UMD bundle only formats the code and has no support for config files, ignore files, CLI usage, or automatic loading of plugins.
### `prettier.format(code, options)`
Unlike the `format` function from the [main API](api.md#prettierformatsource-options), this function does not load plugins automatically, so a `plugins` property is required if you want to load plugins. Additionally, the parsers included in the Prettier package won't be loaded automatically, so you need to load them before using them.
See [Usage](#usage) below for examples.
## Usage
### Global
<!-- prettier-ignore -->
```html
<script src="https://unpkg.com/prettier@1.13.0/standalone.js"></script>
<script src="https://unpkg.com/prettier@1.13.0/parser-graphql.js"></script>
<script type="text/javascript">
prettier.format("query { }", { parser: "graphql", plugins: prettierPlugins });
</script>
```
### AMD
```js
define([
"https://unpkg.com/prettier@1.13.0/standalone.js",
"https://unpkg.com/prettier@1.13.0/parser-graphql.js"
], (prettier, ...plugins) => {
prettier.format("query { }", { parser: "graphql", plugins });
});
```
### CommonJS
```js
const prettier = require("prettier/standalone");
const plugins = [require("prettier/parser-graphql")];
prettier.format("query { }", { parser: "graphql", plugins });
```
This syntax doesn't necessarily work in the browser, but it can be used when bundling the code with browserify, Rollup, webpack, or another bundler.
### Worker
```js
importScripts("https://unpkg.com/prettier@1.13.0/standalone.js");
importScripts("https://unpkg.com/prettier@1.13.0/parser-graphql.js");
prettier.format("query { }", { parser: "graphql", plugins: prettierPlugins });
```

View File

@ -0,0 +1,139 @@
---
id: version-stable-cli
title: CLI
original_id: cli
---
Run Prettier through the CLI with this script. Run it without any arguments to see the [options](options.md).
To format a file in-place, use `--write`. You may want to consider committing your code before doing that, just in case.
```bash
prettier [opts] [filename ...]
```
In practice, this may look something like:
```bash
prettier --single-quote --trailing-comma es5 --write "{app,__{tests,mocks}__}/**/*.js"
```
Don't forget the quotes around the globs! The quotes make sure that Prettier expands the globs rather than your shell, for cross-platform usage. The [glob syntax from the glob module](https://github.com/isaacs/node-glob/blob/master/README.md#glob-primer) is used.
Prettier CLI will ignore files located in `node_modules` directory. To opt-out from this behavior use `--with-node-modules` flag.
## `--debug-check`
If you're worried that Prettier will change the correctness of your code, add `--debug-check` to the command. This will cause Prettier to print an error message if it detects that code correctness might have changed. Note that `--write` cannot be used with `--debug-check`.
## `--find-config-path` and `--config`
If you are repeatedly formatting individual files with `prettier`, you will incur a small performance cost when prettier attempts to look up a [configuration file](configuration.md). In order to skip this, you may ask prettier to find the config file once, and re-use it later on.
```bash
prettier --find-config-path ./my/file.js
./my/.prettierrc
```
This will provide you with a path to the configuration file, which you can pass to `--config`:
```bash
prettier --config ./my/.prettierrc --write ./my/file.js
```
You can also use `--config` if your configuration file lives somewhere where prettier cannot find it, such as a `config/` directory.
If you don't have a configuration file, or want to ignore it if it does exist, you can pass `--no-config` instead.
## `--ignore-path`
Path to a file containing patterns that describe files to ignore. By default, prettier looks for `./.prettierignore`.
## `--require-pragma`
Require a special comment, called a pragma, to be present in the file's first docblock comment in order for prettier to format it.
```js
/**
* @prettier
*/
```
Valid pragmas are `@prettier` and `@format`.
## `--insert-pragma`
Insert a `@format` pragma to the top of formatted files when pragma is absent. Works well when used in tandem with `--require-pragma`.
## `--list-different`
Another useful flag is `--list-different` (or `-l`) which prints the filenames of files that are different from Prettier formatting. If there are differences the script errors out, which is useful in a CI scenario.
```bash
prettier --single-quote --list-different "src/**/*.js"
```
## `--no-config`
Do not look for a configuration file. The default settings will be used.
## `--config-precedence`
Defines how config file should be evaluated in combination of CLI options.
**cli-override (default)**
CLI options take precedence over config file
**file-override**
Config file take precedence over CLI options
**prefer-file**
If a config file is found will evaluate it and ignore other CLI options. If no config file is found CLI options will evaluate as normal.
This option adds support to editor integrations where users define their default configuration but want to respect project specific configuration.
## `--no-editorconfig`
Don't take .editorconfig into account when parsing configuration. See the [`prettier.resolveConfig` docs](./api.md) for details.
## `--with-node-modules`
Prettier CLI will ignore files located in `node_modules` directory. To opt-out from this behavior use `--with-node-modules` flag.
## `--write`
This rewrites all processed files in place. This is comparable to the `eslint --fix` workflow.
## `--loglevel`
Change the level of logging for the CLI. Valid options are:
- `error`
- `warn`
- `log` (default)
- `debug`
- `silent`
## `--stdin-filepath`
A path to the file that the Prettier CLI will treat like stdin. For example:
_abc.css_
```css
.name {
display: none;
}
```
_shell_
```bash
$ cat abc.css | prettier --stdin-filepath abc.css
.name {
display: none;
}
```

View File

@ -0,0 +1,17 @@
---
id: version-stable-comparison
title: Prettier vs. Linters
original_id: comparison
---
## How does it compare to ESLint/TSLint/stylelint, etc.?
Linters have two categories of rules:
**Formatting rules**: eg: [max-len](http://eslint.org/docs/rules/max-len), [no-mixed-spaces-and-tabs](http://eslint.org/docs/rules/no-mixed-spaces-and-tabs), [keyword-spacing](http://eslint.org/docs/rules/keyword-spacing), [comma-style](http://eslint.org/docs/rules/comma-style)...
Prettier alleviates the need for this whole category of rules! Prettier is going to reprint the entire program from scratch in a consistent way, so it's not possible for the programmer to make a mistake there anymore :)
**Code-quality rules**: eg [no-unused-vars](http://eslint.org/docs/rules/no-unused-vars), [no-extra-bind](http://eslint.org/docs/rules/no-extra-bind), [no-implicit-globals](http://eslint.org/docs/rules/no-implicit-globals), [prefer-promise-reject-errors](http://eslint.org/docs/rules/prefer-promise-reject-errors)...
Prettier does nothing to help with those kind of rules. They are also the most important ones provided by linters as they are likely to catch real bugs with your code!

View File

@ -0,0 +1,131 @@
---
id: version-stable-configuration
title: Configuration File
original_id: configuration
---
Prettier uses [cosmiconfig](https://github.com/davidtheclark/cosmiconfig) for configuration file support. This means you can configure prettier via:
- A `.prettierrc` file, written in YAML or JSON, with optional extensions: `.yaml/.yml/.json`.
- A `.prettierrc.toml` file, written in TOML (the `.toml` extension is _required_).
- A `prettier.config.js` or `.prettierrc.js` file that exports an object.
- A `"prettier"` key in your `package.json` file.
The configuration file will be resolved starting from the location of the file being formatted, and searching up the file tree until a config file is (or isn't) found.
The options to the configuration file are the same as the [API options](options.md).
## Basic Configuration
JSON:
```json
{
"trailingComma": "es5",
"tabWidth": 4,
"semi": false,
"singleQuote": true
}
```
JS:
```js
// prettier.config.js or .prettierrc.js
module.exports = {
trailingComma: "es5",
tabWidth: 4,
semi: false,
singleQuote: true
};
```
YAML:
```yaml
# .prettierrc or .prettierrc.yaml
trailingComma: "es5"
tabWidth: 4
semi: false
singleQuote: true
```
TOML:
```toml
# .prettierrc.toml
trailingComma = "es5"
tabWidth = 4
semi = false
singleQuote = true
```
## Configuration Overrides
Prettier borrows eslint's [override format](http://eslint.org/docs/user-guide/configuring#example-configuration). This allows you to apply configuration to specific files.
JSON:
```json
{
"semi": false,
"overrides": [
{
"files": "*.test.js",
"options": {
"semi": true
}
}
]
}
```
YAML:
```yaml
semi: false
overrides:
- files: "*.test.js"
options:
semi: true
```
`files` is required for each override, and may be a string or array of strings. `excludeFiles` may be optionally provided to exclude files for a given rule, and may also be a string or array of strings.
## Setting the [parser](options.md#parser) option
By default, Prettier automatically infers which parser to use based on the input file extension. Combined with `overrides` you can teach Prettier how to parse files it does not recognize.
For example, to get Prettier to format its own `.prettierrc` file, you can do:
```json
{
"overrides": [
{
"files": ".prettierrc",
"options": { "parser": "json" }
}
]
}
```
You can also switch to the `flow` parser instead of the default `babylon` for .js files:
```json
{
"overrides": [
{
"files": "*.js",
"options": {
"parser": "flow"
}
}
]
}
```
**Note:** _Never_ put the `parser` option at the top level of your configuration. _Only_ use it inside `overrides`. Otherwise you effectively disable Prettier's automatic file extension based parser inference. This forces Prettier to use the parser you specified for _all_ types of files even when it doesn't make sense, such as trying to parse a CSS file as JavaScript.
## Configuration Schema
If you'd like a JSON schema to validate your configuration, one is available here: http://json.schemastore.org/prettierrc.

View File

@ -0,0 +1,44 @@
---
id: version-stable-editors
title: Editor Integration
original_id: editors
---
## Atom
Atom users can simply install the [prettier-atom] package and use `Ctrl+Alt+F` to format a file (or format on save if enabled).
Alternatively, you can use one the packages below, which behave similarly to [prettier-atom] but have a focus on minimalism.
- [mprettier](https://github.com/t9md/atom-mprettier)
- [miniprettier](https://github.com/duailibe/atom-miniprettier)
## Emacs
Emacs users should see [this repository](https://github.com/prettier/prettier-emacs) for on-demand formatting.
## Vim
Vim users can install either [vim-prettier](https://github.com/prettier/vim-prettier), which is Prettier specific, or [Neoformat](https://github.com/sbdchd/neoformat) or [ALE](https://github.com/w0rp/ale) which are generalized lint/format engines with support for Prettier.
For more details see [the Vim setup guide](vim.md).
## Visual Studio Code
`prettier-vscode` can be installed using the extension sidebar. Search for `Prettier - Code formatter`. It can also be installed using `ext install prettier-vscode` in the command palette. [Check its repository for configuration and shortcuts](https://github.com/prettier/prettier-vscode).
If you'd like to toggle the formatter on and off, install [`vscode-status-bar-format-toggle`](https://marketplace.visualstudio.com/items?itemName=tombonnike.vscode-status-bar-format-toggle).
## Visual Studio
Install the [JavaScript Prettier extension](https://github.com/madskristensen/JavaScriptPrettier).
## Sublime Text
Sublime Text support is available through Package Control and the [JsPrettier](https://packagecontrol.io/packages/JsPrettier) plug-in.
## JetBrains WebStorm, PHPStorm, PyCharm...
See the [WebStorm setup guide](webstorm.md).
[prettier-atom]: https://github.com/prettier/prettier-atom

View File

@ -0,0 +1,66 @@
---
id: version-stable-eslint
title: Integrating with ESLint
original_id: eslint
---
If you are using ESLint, integrating Prettier to your workflow is straightforward.
There are two different ways you might want to integrate Prettier into ESLint. You may enable either one separately, or use both together.
## Use ESLint to run Prettier
If you're already running ESLint in your project and would like to do all of your style checking with a single command execution, you can ask ESLint to run Prettier for you.
Just add Prettier as an ESLint rule using [eslint-plugin-prettier](https://github.com/prettier/eslint-plugin-prettier).
```bash
yarn add --dev prettier eslint-plugin-prettier
```
.eslintrc.json:
```json
{
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error"
}
}
```
## Turn off ESLint's formatting rules
Whether you run Prettier via ESLint or run both tools separately, you probably only want to hear about each formatting issue once, and you especially don't want ESLint to complain about formatting "issues" which are simply a different preference than what Prettier does.
So you'll probably want to disable the conflicting rules (while keeping around other rules that Prettier doesn't care about). The easiest way to do this is to use [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier). It's a one liner that can be added on-top of any existing ESLint configuration.
```bash
yarn add --dev eslint-config-prettier
```
.eslintrc.json:
```json
{
"extends": ["prettier"]
}
```
There are a few rules that this disables that you may want to turn back on as long as you don't use them with particular options which conflict with Prettier. See [the docs](https://github.com/prettier/eslint-config-prettier#special-rules) for details.
## Use both
`eslint-plugin-prettier` exposes a `"recommended"` configuration that turns on both `eslint-plugin-prettier` and `eslint-config-prettier`, all you need in your `.eslintrc.json` is:
```json
{
"extends": ["plugin:prettier/recommended"]
}
```
Remember to install both `eslint-plugin-prettier` and `eslint-config-prettier`:
```bash
yarn add --dev eslint-plugin-prettier eslint-config-prettier
```

View File

@ -0,0 +1,120 @@
---
id: version-stable-ignore
title: Ignoring Code
original_id: ignore
---
Prettier offers an escape hatch to ignore a block of code or prevent entire files from being formatted.
## Ignoring Files
To exclude files from formatting, add entries to a `.prettierignore` file in the project root or set the [`--ignore-path` CLI option](cli.md#ignore-path).
## JavaScript
A JavaScript comment of `// prettier-ignore` will exclude the next node in the abstract syntax tree from formatting.
For example:
<!-- prettier-ignore -->
```js
matrix(
1, 0, 0,
0, 1, 0,
0, 0, 1
)
// prettier-ignore
matrix(
1, 0, 0,
0, 1, 0,
0, 0, 1
)
```
will be transformed to:
```js
matrix(1, 0, 0, 0, 1, 0, 0, 0, 1);
// prettier-ignore
matrix(
1, 0, 0,
0, 1, 0,
0, 0, 1
)
```
## JSX
```jsx
<div>
{/* prettier-ignore */}
<span ugly format='' />
</div>
```
## HTML
```html
<!-- prettier-ignore -->
<div class="x" >hello world</div >
<!-- prettier-ignore-attribute -->
<div
(mousedown)=" onStart ( ) "
(mouseup)=" onEnd ( ) "
></div>
<!-- prettier-ignore-attribute (mouseup) -->
<div
(mousedown)="onStart()"
(mouseup)=" onEnd ( ) "
></div>
```
## CSS
```css
/* prettier-ignore */
.my ugly rule
{
}
```
## Markdown
```markdown
<!-- prettier-ignore -->
Do not format this
```
### Range Ignore
_available in v1.12.0+_
This type of ignore is only allowed to be used in top-level and aimed to disable formatting for auto-generated content, e.g. [`all-contributors`](https://github.com/kentcdodds/all-contributors), [`markdown-toc`](https://github.com/jonschlinkert/markdown-toc), etc.
```markdown
<!-- prettier-ignore-start -->
<!-- SOMETHING AUTO-GENERATED BY TOOLS - START -->
| MY | AWESOME | AUTO-GENERATED | TABLE |
|-|-|-|-|
| a | b | c | d |
<!-- SOMETHING AUTO-GENERATED BY TOOLS - END -->
<!-- prettier-ignore-end -->
```
## GraphQL
```graphql
{
# prettier-ignore
addReaction(input:{superLongInputFieldName:"MDU6SXNzdWUyMzEzOTE1NTE=",content:HOORAY}) {
reaction {content}
}
}
```

View File

@ -0,0 +1,60 @@
---
id: version-stable-index
title: What is Prettier?
original_id: index
---
Prettier is an opinionated code formatter with support for:
- JavaScript, including [ES2017](https://github.com/tc39/proposals/blob/master/finished-proposals.md)
- [JSX](https://facebook.github.io/jsx/)
- [Angular](https://angular.io/)
- [Vue](https://vuejs.org/)
- [Flow](https://flow.org/)
- [TypeScript](https://www.typescriptlang.org/)
- CSS, [Less](http://lesscss.org/), and [SCSS](http://sass-lang.com)
- [HTML](https://en.wikipedia.org/wiki/HTML)
- [JSON](http://json.org/)
- [GraphQL](http://graphql.org/)
- [Markdown](http://commonmark.org/), including [GFM](https://github.github.com/gfm/) and [MDX](https://mdxjs.com/)
- [YAML](http://yaml.org/)
It removes all original styling[\*](#footnotes) and ensures that all outputted code conforms to a consistent style. (See this [blog post](http://jlongster.com/A-Prettier-Formatter))
Prettier takes your code and reprints it from scratch by taking the line length into account.
For example, take the following code:
```js
foo(arg1, arg2, arg3, arg4);
```
It fits in a single line so it's going to stay as is. However, we've all run into this situation:
<!-- prettier-ignore -->
```js
foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne());
```
Suddenly our previous format for calling function breaks down because this is too long. Prettier is going to do the painstaking work of reprinting it like that for you:
```js
foo(
reallyLongArg(),
omgSoManyParameters(),
IShouldRefactorThis(),
isThereSeriouslyAnotherOne()
);
```
Prettier enforces a consistent code **style** (i.e. code formatting that won't affect the AST) across your entire codebase because it disregards the original styling[\*](#footnotes) by parsing it away and re-printing the parsed AST with its own rules that take the maximum line length into account, wrapping code when necessary.
If you want to learn more, these two conference talks are great introductions:
[![A Prettier Printer by James Long on React Conf 2017](/docs/assets/youtube-cover/a-prettier-printer-by-james-long-on-react-conf-2017.png)](https://www.youtube.com/watch?v=hkfBvpEfWdA)
[![JavaScript Code Formatting by Christopher Chedeau on React London 2017](/docs/assets/youtube-cover/javascript-code-formatting-by-christopher-chedeau-on-react-london-2017.png)](https://www.youtube.com/watch?v=0Q4kUNx85_4)
#### Footnotes
\* _Well actually, some original styling is preserved when practical—see [empty lines](rationale.md#empty-lines) and [multi-line objects](rationale.md#multi-line-objects)._

View File

@ -0,0 +1,23 @@
---
id: version-stable-install
title: Install
original_id: install
---
Install with `yarn`:
```bash
yarn add prettier --dev --exact
# or globally
yarn global add prettier
```
_We're using `yarn` but you can use `npm` if you like:_
```bash
npm install --save-dev --save-exact prettier
# or globally
npm install --global prettier
```
> We recommend pinning an exact version of prettier in your `package.json` as we introduce stylistic changes in patch releases.

View File

@ -0,0 +1,32 @@
---
id: version-stable-option-philosophy
title: Option Philosophy
original_id: option-philosophy
---
Prettier is not a kitchen-sink code formatter that attempts to print your code in any way you wish. It is _opinionated._ Quoting the [Why Prettier?](why-prettier.md) page:
> By far the biggest reason for adopting Prettier is to stop all the on-going debates over styles.
The more options Prettier has, the further from the above goal it gets. **The debates over styles just turn into debates over which Prettier options to use.**
The issue about [resisting adding configuration](https://github.com/prettier/prettier/issues/40) has more 👍s than any option request issue.
So why does Prettier have options at all?
Well, had Prettier been created around the same time as JavaScript itself was born it could have made choices that the community would have picked up (which is the case for [elm-format](https://github.com/avh4/elm-format/)). But JavaScript is far older than Prettier so the community has had time to start their holy wars about tabs vs spaces, single vs double quotes, indentation levels, trailing commas and semicolons, so Prettier more or less has to support those.
Then there's a bunch of interesting cases.
- `--trailing-comma es5` was added to make it easier to use trailing commas in most environments without having to transpile (trailing function commas were added in ES2017).
- `--prose-wrap` is important to support all quirky markdown renderers in the wild.
- `--html-whitespace-sensitivity` is needed due to the unfortunate whitespace rules of HTML.
- `--end-of-line` makes it easier for teams to keep CRLFs out of their git repositories.
- `--arrow-parens` was added after at the time [huge demand](https://github.com/prettier/prettier/issues/812). Prettier has to strike a balance between ideal goals and listening to the community.
- `--jsx-single-quote` was also added after [great demand](https://github.com/prettier/prettier/issues/1080), but after more consideration. It took quite some time to figure out the right approach.
- `--jsx-bracket-same-line` was needed for a big company with a huge code base (Facebook), which backed the project when it got started, to be able to [adopt Prettier at all](https://github.com/prettier/prettier/pull/661#issuecomment-295770645).
Finally, perhaps the most interesting of them all is `--bracket-spacing`.
The truth is that not even [Prettier's creator knows exactly why it exists](https://github.com/prettier/prettier/issues/715#issuecomment-281096495). It was added super early on without much thought. It now serves as an example of the types of options we should avoid.
Remember, it is easy to _add_ features to a program, but hard to remove them.

View File

@ -0,0 +1,331 @@
---
id: version-stable-options
title: Options
original_id: options
---
Prettier ships with a handful of customizable format options, usable in both the CLI and API.
## Print Width
Specify the line length that the printer will wrap on.
> **For readability we recommend against using more than 80 characters:**
>
> In code styleguides, maximum line length rules are often set to 100 or 120. However, when humans write code, they don't strive to reach the maximum number of columns on every line. Developers often use whitespace to break up long lines for readability. In practice, the average line length often ends up well below the maximum.
>
> Prettier, on the other hand, strives to fit the most code into every line. With the print width set to 120, prettier may produce overly compact, or otherwise undesirable code.
>
> See the [print width rationale](rationale.md#print-width) for more information.
| Default | CLI Override | API Override |
| ------- | --------------------- | ------------------- |
| `80` | `--print-width <int>` | `printWidth: <int>` |
(If you don't want line wrapping when formatting Markdown, you can set the [Prose Wrap](#prose-wrap) option to disable it.)
## Tab Width
Specify the number of spaces per indentation-level.
| Default | CLI Override | API Override |
| ------- | ------------------- | ----------------- |
| `2` | `--tab-width <int>` | `tabWidth: <int>` |
## Tabs
Indent lines with tabs instead of spaces.
| Default | CLI Override | API Override |
| ------- | ------------ | ----------------- |
| `false` | `--use-tabs` | `useTabs: <bool>` |
(Tabs will be used for _indentation_ but Prettier uses spaces to _align_ things, such as in ternaries.)
## Semicolons
Print semicolons at the ends of statements.
Valid options:
- `true` - Add a semicolon at the end of every statement.
- `false` - Only add semicolons at the beginning of lines that [may introduce ASI failures](rationale.md#semicolons).
| Default | CLI Override | API Override |
| ------- | ------------ | -------------- |
| `true` | `--no-semi` | `semi: <bool>` |
## Quotes
Use single quotes instead of double quotes.
Notes:
- JSX quotes ignore this option see [jsx-single-quote](#jsx-quotes).
- If the number of quotes outweighs the other quote, the quote which is less used will be used to format the string - Example: `"I'm double quoted"` results in `"I'm double quoted"` and `"This \"example\" is single quoted"` results in `'This "example" is single quoted'`.
See the [strings rationale](rationale.md#strings) for more information.
| Default | CLI Override | API Override |
| ------- | ---------------- | --------------------- |
| `false` | `--single-quote` | `singleQuote: <bool>` |
## JSX Quotes
Use single quotes instead of double quotes in JSX.
| Default | CLI Override | API Override |
| ------- | -------------------- | ------------------------ |
| `false` | `--jsx-single-quote` | `jsxSingleQuote: <bool>` |
## Trailing Commas
Print trailing commas wherever possible when multi-line. (A single-line array, for example, never gets trailing commas.)
Valid options:
- `"none"` - No trailing commas.
- `"es5"` - Trailing commas where valid in ES5 (objects, arrays, etc.)
- `"all"` - Trailing commas wherever possible (including function arguments). This requires node 8 or a [transform](https://babeljs.io/docs/plugins/syntax-trailing-function-commas/).
| Default | CLI Override | API Override |
| -------- | ------------------------------------------------------ | ------------------------------------------------------ |
| `"none"` | <code>--trailing-comma <none&#124;es5&#124;all></code> | <code>trailingComma: "<none&#124;es5&#124;all>"</code> |
## Bracket Spacing
Print spaces between brackets in object literals.
Valid options:
- `true` - Example: `{ foo: bar }`.
- `false` - Example: `{foo: bar}`.
| Default | CLI Override | API Override |
| ------- | ---------------------- | ------------------------ |
| `true` | `--no-bracket-spacing` | `bracketSpacing: <bool>` |
## JSX Brackets
Put the `>` of a multi-line JSX element at the end of the last line instead of being alone on the next line (does not apply to self closing elements).
Valid options:
- `true` - Example:
<!-- prettier-ignore -->
```
<button
className="prettier-class"
id="prettier-id"
onClick={this.handleClick}>
Click Here
</button>
```
- `false` - Example:
<!-- prettier-ignore -->
```
<button
className="prettier-class"
id="prettier-id"
onClick={this.handleClick}
>
Click Here
</button>
```
| Default | CLI Override | API Override |
| ------- | ------------------------- | ---------------------------- |
| `false` | `--jsx-bracket-same-line` | `jsxBracketSameLine: <bool>` |
## Arrow Function Parentheses
_First available in v1.9.0_
Include parentheses around a sole arrow function parameter.
Valid options:
- `"avoid"` - Omit parens when possible. Example: `x => x`
- `"always"` - Always include parens. Example: `(x) => x`
| Default | CLI Override | API Override |
| --------- | ----------------------------------------------- | ----------------------------------------------- |
| `"avoid"` | <code>--arrow-parens <avoid&#124;always></code> | <code>arrowParens: "<avoid&#124;always>"</code> |
## Range
Format only a segment of a file.
These two options can be used to format code starting and ending at a given character offset (inclusive and exclusive, respectively). The range will extend:
- Backwards to the start of the first line containing the selected statement.
- Forwards to the end of the selected statement.
These options cannot be used with `cursorOffset`.
| Default | CLI Override | API Override |
| ---------- | --------------------- | ------------------- |
| `0` | `--range-start <int>` | `rangeStart: <int>` |
| `Infinity` | `--range-end <int>` | `rangeEnd: <int>` |
## Parser
Specify which parser to use.
Prettier automatically infers the parser from the input file path, so you shouldn't have to change this setting.
Both the `babylon` and `flow` parsers support the same set of JavaScript features (including Flow type annotations). They might differ in some edge cases, so if you run into one of those you can try `flow` instead of `babylon`.
Valid options:
- `"babylon"` (via [@babel/parser](https://github.com/babel/babel/tree/master/packages/babel-parser))
- `"flow"` (via [flow-parser](https://github.com/facebook/flow/tree/master/src/parser))
- `"typescript"` (via [typescript-estree](https://github.com/JamesHenry/typescript-estree)) _First available in v1.4.0_
- `"css"` (via [postcss-scss](https://github.com/postcss/postcss-scss) and [postcss-less](https://github.com/shellscape/postcss-less), autodetects which to use) _First available in v1.7.1_
- `"scss"` (same parsers as `"css"`, prefers postcss-scss) _First available in v1.7.1_
- `"less"` (same parsers as `"css"`, prefers postcss-less) _First available in v1.7.1_
- `"json"` (via [@babel/parser parseExpression](https://babeljs.io/docs/en/next/babel-parser.html#babelparserparseexpressioncode-options)) _First available in v1.5.0_
- `"json5"` (same parser as `"json"`, but outputs as [json5](https://json5.org/)) _First available in v1.13.0_
- `"json-stringify"` (same parser as `"json"`, but outputs like `JSON.stringify`) _First available in v1.13.0_
- `"graphql"` (via [graphql/language](https://github.com/graphql/graphql-js/tree/master/src/language)) _First available in v1.5.0_
- `"markdown"` (via [remark-parse](https://github.com/wooorm/remark/tree/master/packages/remark-parse)) _First available in v1.8.0_
- `"mdx"` (via [remark-parse](https://github.com/wooorm/remark/tree/master/packages/remark-parse) and [@mdx-js/mdx](https://github.com/mdx-js/mdx/tree/master/packages/mdx)) _First available in v1.15.0_
- `"html"` (via [angular-html-parser](https://github.com/ikatyang/angular-html-parser/tree/master/packages/angular-html-parser)) _First available in 1.15.0_
- `"vue"` (same parser as `"html"`, but also formats vue-specific syntax) _First available in 1.10.0_
- `"angular"` (same parser as `"html"`, but also formats angular-specific syntax via [angular-estree-parser](https://github.com/ikatyang/angular-estree-parser)) _First available in 1.15.0_
- `"yaml"` (via [yaml](https://github.com/eemeli/yaml) and [yaml-unist-parser](https://github.com/ikatyang/yaml-unist-parser)) _First available in 1.14.0_
[Custom parsers](api.md#custom-parser-api) are also supported. _First available in v1.5.0_
| Default | CLI Override | API Override |
| ------- | ----------------------------------------------- | ---------------------------------------------------------- |
| None | `--parser <string>`<br />`--parser ./my-parser` | `parser: "<string>"`<br />`parser: require("./my-parser")` |
Note: the default value was `"babylon"` until v1.13.0.
<a name="filepath"></a>
## File Path
Specify the file name to use to infer which parser to use.
For example, the following will use the CSS parser:
```bash
cat foo | prettier --stdin-filepath foo.css
```
| Default | CLI Override | API Override |
| ------- | --------------------------- | ---------------------- |
| None | `--stdin-filepath <string>` | `filepath: "<string>"` |
## Require pragma
_First available in v1.7.0_
Prettier can restrict itself to only format files that contain a special comment, called a pragma, at the top of the file. This is very useful when gradually transitioning large, unformatted codebases to prettier.
For example, a file with the following as its first comment will be formatted when `--require-pragma` is supplied:
```js
/**
* @prettier
*/
```
or
```js
/**
* @format
*/
```
| Default | CLI Override | API Override |
| ------- | ------------------ | ----------------------- |
| `false` | `--require-pragma` | `requirePragma: <bool>` |
## Insert Pragma
_First available in v1.8.0_
Prettier can insert a special @format marker at the top of files specifying that the file has been formatted with prettier. This works well when used in tandem with the `--require-pragma` option. If there is already a docblock at the top of the file then this option will add a newline to it with the @format marker.
| Default | CLI Override | API Override |
| ------- | ----------------- | ---------------------- |
| `false` | `--insert-pragma` | `insertPragma: <bool>` |
## Prose Wrap
_First available in v1.8.2_
By default, Prettier will wrap markdown text as-is since some services use a linebreak-sensitive renderer, e.g. GitHub comment and BitBucket. In some cases you may want to rely on editor/viewer soft wrapping instead, so this option allows you to opt out with `"never"`.
Valid options:
- `"always"` - Wrap prose if it exceeds the print width.
- `"never"` - Do not wrap prose.
- `"preserve"` - Wrap prose as-is. _First available in v1.9.0_
| Default | CLI Override | API Override |
| ------------ | ----------------------------------------------------------- | ----------------------------------------------------------- |
| `"preserve"` | <code>--prose-wrap <always&#124;never&#124;preserve></code> | <code>proseWrap: "<always&#124;never&#124;preserve>"</code> |
## HTML Whitespace Sensitivity
_First available in v1.15.0_
Specify the global whitespace sensitivity for HTML files, see [whitespace-sensitive formatting] for more info.
[whitespace-sensitive formatting]: https://prettier.io/blog/2018/11/07/1.15.0.html#whitespace-sensitive-formatting
Valid options:
- `"css"` - Respect the default value of CSS `display` property.
- `"strict"` - Whitespaces are considered sensitive.
- `"ignore"` - Whitespaces are considered insensitive.
| Default | CLI Override | API Override |
| ------- | ------------------------------------------------------------------------ | ----------------------------------------------------------------------- |
| `"css"` | <code>--html-whitespace-sensitivity <css&#124;strict&#124;ignore></code> | <code>htmlWhitespaceSensitivity: "<css&#124;strict&#124;ignore>"</code> |
## End of Line
_First available in 1.15.0_
For historical reasons, there exist two commonly used flavors of line endings in text files. That is `\n` (or `LF` for _Line Feed_) and `\r\n` (or `CRLF` for _Carriage Return + Line Feed_).
The former is common on Linux and macOS, while the latter is prevalent on Windows.
Some details explaining why it is so [can be found on Wikipedia](https://en.wikipedia.org/wiki/Newline).
By default, Prettier preserves a flavor of line endings a given file has already used.
It also converts mixed line endings within one file to what it finds at the end of the first line.
When people collaborate on a project from different operating systems, it becomes easy to end up with mixed line endings in the central git repository.
It is also possible for Windows users to accidentally change line endings in an already committed file from `LF` to `CRLF`.
Doing so produces a large `git diff`, and if it get unnoticed during code review, all line-by-line history for the file (`git blame`) gets lost.
If you want to make sure that your git repository only contains Linux-style line endings in files covered by Prettier:
1. Set `endOfLine` option to `lf`
1. Configure [a pre-commit hook](./precommit.md) that will run Prettier
1. Configure Prettier to run in your CI pipeline (e.g. using [`prettier-check` npm package](https://www.npmjs.com/package/prettier-check))
1. Ask Windows users to run `git config core.autocrlf false` before working on your repo so that git did not convert `LF` to `CRLF` on checkout.
Alternatively, you can add `* text=auto eol=lf` to the repo's `.gitattributes` file to achieve this.
All modern text editors in all operating systems are able to correctly display line endings when `\n` (`LF`) is used.
However, old versions of Notepad for Windows will visually squash such lines into one.
Valid options:
- `"auto"` - Maintain existing line endings
(mixed values within one file are normalised by looking at what's used after the first line)
- `"lf"` Line Feed only (`\n`), common on Linux and macOS as well as inside git repos
- `"crlf"` - Carriage Return + Line Feed characters (`\r\n`), common on Windows
- `"cr"` - Carriage Return character only (`\r`), used very rarely
| Default | CLI Override | API Override |
| -------- | ----------------------------------------------------------- | ---------------------------------------------------------- |
| `"auto"` | <code>--end-of-line <auto&#124;lf&#124;crlf&#124;cr></code> | <code>endOfLine: "<auto&#124;lf&#124;crlf&#124;cr>"</code> |

View File

@ -0,0 +1,261 @@
---
id: version-stable-plugins
title: Plugins (Beta)
original_id: plugins
---
## IN BETA
> The plugin API is in a **beta** state as of Prettier 1.10 and the API may change in the next release!
Plugins are ways of adding new languages to Prettier. Prettier's own implementations of all languages are expressed using the plugin API. The core `prettier` package contains JavaScript and other web-focused languages built in. For additional languages you'll need to install a plugin.
## Using Plugins
Plugins are automatically loaded if you have them installed in the same `node_modules` directory where `prettier` is located. Plugin package names must start with `@prettier/plugin-` or `prettier-plugin-` to be registered.
When plugins cannot be found automatically, you can load them with:
- The [CLI](./cli.md), via the `--plugin` and `--plugin-search-dir`:
```bash
prettier --write main.foo --plugin-search-dir=./dir-with-plugins --plugin=./foo-plugin
```
> Tip: You can set `--plugin` or `--plugin-search-dir` options multiple times.
- Or the [API](./api.md), via the `plugins` and `pluginSearchDirs` options:
```js
prettier.format("code", {
parser: "foo",
pluginSearchDirs: ["./dir-with-plugins"],
plugins: ["./foo-plugin"]
});
```
Prettier expects each of `pluginSearchDirs` to contain `node_modules` subdirectory, where `@prettier/plugin-*` and `prettier-plugin-*` will be searched. For instance, this can be your project directory or the location of global npm modules.
Providing at least one path to `--plugin-search-dir`/`pluginSearchDirs` turns off plugin autoloading in the default directory (i.e. `node_modules` above `prettier` binary).
## Official Plugins
- [`@prettier/plugin-python`](https://github.com/prettier/plugin-python)
- [`@prettier/plugin-php`](https://github.com/prettier/plugin-php)
- [`@prettier/plugin-swift`](https://github.com/prettier/plugin-swift)
## Community Plugins
- [`prettier-plugin-apex`](https://github.com/dangmai/prettier-plugin-apex) by [**@dangmai**](https://github.com/dangmai)
- [`prettier-plugin-elm`](https://github.com/gicentre/prettier-plugin-elm) by [**@giCentre**](https://github.com/gicentre)
- [`prettier-plugin-java`](https://github.com/thorbenvh8/prettier-java) by [**@thorbenvh8**](https://github.com/thorbenvh8)
- [`prettier-plugin-pg`](https://github.com/benjie/prettier-plugin-pg) by [**@benjie**](https://github.com/benjie)
- [`prettier-plugin-ruby`](https://github.com/iamsolankiamit/prettier-ruby) by [**@iamsolankiamit**](https://github.com/iamsolankiamit)
## Developing Plugins
Prettier plugins are regular JavaScript modules with five exports:
- `languages`
- `parsers`
- `printers`
- `options`
- `defaultOptions`
### `languages`
Languages is an array of language definitions that your plugin will contribute to Prettier. It can include all of the fields specified in [`prettier.getSupportInfo()`](./api.md#prettiergetsupportinfo-version).
It **must** include `name` and `parsers`.
```js
export const languages = [
{
// The language name
name: "InterpretedDanceScript",
// Parsers that can parse this language.
// This can be built-in parsers, or parsers you have contributed via this plugin.
parsers: ["dance-parse"]
}
];
```
### `parsers`
Parsers convert code as a string into an [AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree).
The key must match the name in the `parsers` array from `languages`. The value contains a parse function, an AST format name, and two location extraction functions (`locStart` and `locEnd`).
```js
export const parsers = {
"dance-parse": {
parse,
// The name of the AST that
astFormat: "dance-ast",
hasPragma,
locStart,
locEnd,
preprocess
}
};
```
The signature of the `parse` function is:
```ts
function parse(text: string, parsers: object, options: object): AST;
```
The location extraction functions (`locStart` and `locEnd`) return the starting and ending locations of a given AST node:
```ts
function locStart(node: object): number;
```
_(Optional)_ The pragma detection function (`hasPragma`) should return if the text contains the pragma comment.
```ts
function hasPragma(text: string): boolean;
```
_(Optional)_ The preprocess function can process the input text before passing into `parse` function.
```ts
function preprocess(text: string, options: object): string;
```
### `printers`
Printers convert ASTs into a Prettier intermediate representation, also known as a Doc.
The key must match the `astFormat` that the parser produces. The value contains an object with a `print` function and (optionally) an `embed` function.
```js
export const printers = {
"dance-ast": {
print,
embed,
insertPragma
}
};
```
Printing is a recursive process of converting an AST node (represented by a path to that node) into a doc. The doc is constructed using the [builder commands](https://github.com/prettier/prettier/blob/master/commands.md):
```js
const { concat, join, line, ifBreak, group } = require("prettier").doc.builders;
```
The signature of the `print` function is:
```ts
function print(
// Path to the AST node to print
path: FastPath,
options: object,
// Recursively print a child node
print: (path: FastPath) => Doc
): Doc;
```
Check out [prettier-python's printer](https://github.com/prettier/prettier-python/blob/034ba8a9551f3fa22cead41b323be0b28d06d13b/src/printer.js#L174) as an example.
Embedding refers to printing one language inside another. Examples of this are CSS-in-JS and Markdown code blocks. Plugins can switch to alternate languages using the `embed` function. Its signature is:
```ts
function embed(
// Path to the current AST node
path: FastPath,
// Print a node with the current printer
print: (path: FastPath) => Doc,
// Parse and print some text using a different parser.
// You should set `options.parser` to specify which parser to use.
textToDoc: (text: string, options: object) => Doc,
// Current options
options: object
): Doc | null;
```
If you don't want to switch to a different parser, simply return `null` or `undefined`.
A plugin can implement how a pragma comment is inserted in the resulting code when the `--insert-pragma` option is used, in the `insertPragma` function. Its signature is:
```ts
function insertPragma(text: string): string;
```
_(Optional)_ The preprocess function can process the ast from parser before passing into `print` function.
```ts
function preprocess(ast: AST, options: object): AST;
```
### `options`
`options` is an object containing the custom options your plugin supports.
Example:
```js
options: {
openingBraceNewLine: {
type: "boolean",
category: "Global",
default: true,
description: "Move open brace for code blocks onto new line."
}
}
```
### `defaultOptions`
If your plugin requires different default values for some of Prettier's core options, you can specify them in `defaultOptions`:
```
defaultOptions: {
tabWidth: 4
}
```
### Utility functions
A `util` module from Prettier core is considered a private API and is not meant to be consumed by plugins. Instead, the `util-shared` module provides the following limited set of utility functions for plugins:
```ts
getMaxContinuousCount(str: string, target: string): number;
getStringWidth(text: string): number;
getAlignmentSize(value: string, tabWidth: number, startIndex: number): number;
getIndentSize(value: string, tabWidth: number): number;
skip(chars: string|RegExp): number;
skipWhitespace(text: string, index: number, options: object): number;
skipSpaces(text: string, index: number, options: object): number;
skipToLineEnd(text: string, index: number, options: object): number;
skipEverythingButNewLine(text: string, index: number, options: object): number;
skipInlineComment(text: string, index: number): number;
skipTrailingComment(text: string, index: number): number;
skipNewline(text: string, index: number, options: object): number;
hasNewline(text: string, index: number, options: object): boolean;
hasNewlineInRange(text: string, start: number, start: number): boolean;
hasSpaces(text: string, index: number, options: object): number;
makeString(rawContent: string, enclosingQuote: string, unescapeUnnecessarEscapes: boolean): string;
getNextNonSpaceNonCommentCharacterIndex(text: string, node: object, options: object): number;
isNextLineEmptyAfterIndex(text: string, index: number): boolean;
isNextLineEmpty(text: string, node: object, options: object): boolean;
isPreviousLineEmpty(text: string, node: object, options: object): boolean;
mapDoc(doc: object, callback: function): void;
```
## Testing Plugins
Since plugins can be resolved using relative paths, when working on one you can do:
```js
const prettier = require("prettier");
const code = "(add 1 2)";
prettier.format(code, {
parser: "lisp",
plugins: ["."]
});
```
This will resolve a plugin relative to the current working directory.

View File

@ -0,0 +1,126 @@
---
id: version-stable-precommit
title: Pre-commit Hook
original_id: precommit
---
You can use Prettier with a pre-commit tool. This can re-format your files that are marked as "staged" via `git add` before you commit.
## Option 1. [lint-staged](https://github.com/okonet/lint-staged)
**Use Case:** Useful for when you need to use other tools on top of Prettier (e.g. ESLint)
Install it along with [husky](https://github.com/typicode/husky):
```bash
yarn add lint-staged husky --dev
```
and add this config to your `package.json`:
```json
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,json,css,md}": ["prettier --write", "git add"]
}
}
```
See https://github.com/okonet/lint-staged#configuration for more details about how you can configure lint-staged.
## Option 2. [pretty-quick](https://github.com/azz/pretty-quick)
**Use Case:** Great for when you want an entire file formatting on your changed/staged files.
Install it along with [husky](https://github.com/typicode/husky):
```bash
yarn add pretty-quick husky --dev
```
and add this config to your `package.json`:
```json
{
"husky": {
"hooks": {
"pre-commit": "pretty-quick --staged"
}
}
}
```
Find more info from [here](https://github.com/azz/pretty-quick).
## Option 3. [pre-commit](https://github.com/pre-commit/pre-commit)
**Use Case:** Great when working with multi-language projects.
Copy the following config into your `.pre-commit-config.yaml` file:
```yaml
- repo: https://github.com/prettier/prettier
rev: "" # Use the sha or tag you want to point at
hooks:
- id: prettier
```
Find more info from [here](https://pre-commit.com).
## Option 4. [precise-commits](https://github.com/JamesHenry/precise-commits)
**Use Case:** Great for when you want partial file formatting on your changed/staged files.
Install it along with [husky](https://github.com/typicode/husky):
```bash
yarn add precise-commits husky --dev
```
and add this config to your `package.json`:
```json
{
"husky": {
"hooks": {
"pre-commit": "precise-commits"
}
}
}
```
**Note:** This is currently the only tool that will format only staged lines rather than the entire file. See more information [here](https://github.com/JamesHenry/precise-commits#why-precise-commits)
Read more about this tool [here](https://github.com/JamesHenry/precise-commits#2-precommit-hook).
## Option 5. bash script
Alternately you can save this script as `.git/hooks/pre-commit` and give it execute permission:
```bash
#!/bin/sh
jsfiles=$(git diff --cached --name-only --diff-filter=ACM "*.js" "*.jsx" | tr '\n' ' ')
[ -z "$jsfiles" ] && exit 0
# Prettify all staged .js files
echo "$jsfiles" | xargs ./node_modules/.bin/prettier --write
# Add back the modified/prettified files to staging
echo "$jsfiles" | xargs git add
exit 0
```
If git is reporting that your prettified files are still modified after committing, you may need to add a post-commit script to update git's index as described in [this issue](https://github.com/prettier/prettier/issues/2978#issuecomment-334408427).
Add something like the following to `.git/hooks/post-commit`:
```bash
#!/bin/sh
git update-index -g
```

View File

@ -0,0 +1,315 @@
---
id: version-stable-rationale
title: Rationale
original_id: rationale
---
Prettier is an opinionated code formatter. This document explains some of its choices.
## What Prettier is concerned about
### Correctness
The first requirement of Prettier is to output valid code that has the exact same behavior as before formatting. Please report any code where Prettier fails to follow these correctness rules — that's a bug which needs to be fixed!
### Strings
Double or single quotes? Prettier chooses the one which results in the fewest number of escapes. `"It's gettin' better!"`, not `'It\'s gettin\' better!'`. In case of a tie, Prettier defaults to double quotes (but that can be changed via the [`--single-quote`](options.html#quotes) option).
JSX has its own option for quotes: [`--jsx-single-quote`](options.html#jsx-quotes).
JSX takes its roots from HTML, where the dominant use of quotes for attributes is double quotes. Browser developer tools also follow this convention by always displaying HTML with double quotes, even if the source code uses single quotes. A separate option allows using single quotes for JS and double quotes for "HTML" (JSX).
Prettier maintains the way your string is escaped. For example, `"🙂"` won't be formatted into `"\uD83D\uDE42"` and vice versa.
### Empty lines
It turns out that empty lines are very hard to automatically generate. The approach that Prettier takes is to preserve empty lines the way they were in the original source code. There are two additional rules:
- Prettier collapses multiple blank lines into a single blank line.
- Empty lines at the start and end of blocks (and whole files) are removed. (Files always end with a single newline, though.)
### Multi-line objects
By default, Prettiers printing algorithm prints expressions on a single line if they fit. Objects are used for a lot of different things in JavaScript, though, and sometimes it really helps readability if they stay multiline. See [object lists], [nested configs], [stylesheets] and [keyed methods], for example. We haven't been able to find a good rule for all those cases, so Prettier instead keeps objects multiline if there's a newline between the `{` and the first key in the original source code. A consequence of this is that long singleline objects are automatically expanded, but short multiline objects are never collapsed.
**Tip:** If you have a multiline object that you'd like to join up into a single line:
```js
const user = {
name: "John Doe",
age: 30
};
```
…all you need to do is remove the newline after `{`:
<!-- prettier-ignore -->
```js
const user = { name: "John Doe",
age: 30
};
```
…and then run Prettier:
```js
const user = { name: "John Doe", age: 30 };
```
And if you'd like to go multiline again, add in a newline after `{`:
<!-- prettier-ignore -->
```js
const user = {
name: "John Doe", age: 30 };
```
…and run Prettier:
```js
const user = {
name: "John Doe",
age: 30
};
```
[object lists]: https://github.com/prettier/prettier/issues/74#issue-199965534
[nested configs]: https://github.com/prettier/prettier/issues/88#issuecomment-275448346
[stylesheets]: https://github.com/prettier/prettier/issues/74#issuecomment-275262094
[keyed methods]: https://github.com/prettier/prettier/pull/495#issuecomment-275745434
### Decorators
Just like with objects, decorators are used for a lot of different things. Sometimes it makes sense to write decorators _above_ the line they're decorating, sometimes it's nicer if they're on the _same_ line. We haven't been able to find a good rule for this, so Prettier keeps your decorator positioned like you wrote them (if they fit on the line). This isn't ideal, but a pragmatic solution to a difficult problem.
```js
@Component({
selector: "hero-button",
template: `<button>{{label}}</button>`
})
class HeroButtonComponent {
// These decorators were written inline and fit on the line so they stay
// inline.
@Output() change = new EventEmitter();
@Input() label: string;
// These were written multiline, so they stay multiline.
@readonly
@nonenumerable
NODE_TYPE: 2;
}
```
There's one exception: classes. We don't think it ever makes sense to inline the decorators for them, so they are always moved to their own line.
<!-- prettier-ignore -->
```js
// Before running Prettier:
@observer class OrderLine {
@observable price: number = 0;
}
```
```js
// After running Prettier:
@observer
class OrderLine {
@observable price: number = 0;
}
```
Note: Prettier 1.14.x and older tried to automatically move your decorators, so if you've run an older Prettier version on your code you might need to manually join up some decorators here and there to avoid inconsistencies:
```js
@observer
class OrderLine {
@observable price: number = 0;
@observable
amount: number = 0;
}
```
One final thing: TC39 has [not yet decided if decorators come before or after `export`](https://github.com/tc39/proposal-decorators/issues/69). In the meantime, Prettier supports both:
```js
@decorator
export class Foo { }
export @decorator class Foo { }
```
### Semicolons
This is about using the [`--no-semi`](options.md#semicolons) option.
Consider this piece of code:
<!-- prettier-ignore -->
```js
if (shouldAddLines) {
[-1, 1].forEach(delta => addLine(delta * 20))
}
```
While the above code works just fine without semicolons, Prettier actually turns it into:
<!-- prettier-ignore -->
```js
if (shouldAddLines) {
;[-1, 1].forEach(delta => addLine(delta * 20))
}
```
This is to help you avoid mistakes. Imagine Prettier _not_ inserting that semicolon and 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:
<!-- prettier-ignore -->
```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
### Print width
The [`--print-width`](options.md#print-width) is more of a guideline to Prettier than a hard rule. It generally means “try to make lines this long, go shorter if needed and longer in special cases.”
There are some edge cases, such as really long string literals, regexps, comments and variable names, which cannot be broken across lines (without using code transforms which [Prettier doesnt do](#what-prettier-is-not-concerned-about)). Or if you nest your code 50 levels deep your lines are of course going to be mostly indentation :)
Apart from that, there are a few cases where Prettier intentionally exceeds the print width.
#### 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.
#### Testing functions
Another common request was to keep lengthy test descriptions in one line, even if it gets too long. In such cases, wrapping the arguments to new lines doesnt help much.
```js
describe("NodeRegistry", () => {
it("makes no request if there are no nodes to prefetch, even if the cache is stale", async () => {
// The above line exceeds the print width but stayed on one line anyway.
});
});
```
Prettier has special cases for common testing framework functions such as `describe`, `it` and `test`.
### 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 (
<div>
{user ? (
<p>Welcome back, {user.name}!</p>
) : (
<p>Greetings, traveler! Sign up today!</p>
)}
</div>
);
}
```
There are two reasons.
First off, lots of people already wrapped their JSX in parentheses, especially in `return` statements. Prettier follows this common style.
Secondly, [the alternate formatting makes it easier to edit the JSX](https://github.com/prettier/prettier/issues/2208). It is easy to leave a semicolon behind. As opposed to normal JS, a leftover semicolon in JSX can end up as plain text showing on your page.
```jsx
<div>
<p>Greetings, traveler! Sign up today!</p>; {/* <-- Oops! */}
</div>
```
### Comments
When it comes to the _contents_ of comments, Prettier cant do much really. Comments can contain everything from prose to commented out code and ASCII diagrams. Since they can contain anything, Prettier cant know how to format or wrap them. So they are left as-is. The only exception to this are JSDoc-style comments (block comments where every line starts with a `*`), which Prettier can fix the indentation of.
Then theres the question of _where_ to put the comments. Turns out this is a really difficult problem. Prettier tries it best to keep your comments roughly where they where, but its no easy task because comments can be placed almost anywhere.
Generally, you get the best results when placing comments **on their own lines,** instead of at the end of lines. Prefer `// eslint-disable-next-line` over `// eslint-disable-line`.
Note that “magic comments” such as `eslint-disable-next-line` and `$FlowFixMe` might sometimes need to be manually moved due to Prettier breaking an expression into multiple lines.
Imagine this piece of code:
```js
// eslint-disable-next-line no-eval
const result = safeToEval ? eval(input) : fallback(input);
```
Then you need to add another condition:
<!-- prettier-ignore -->
```js
// eslint-disable-next-line no-eval
const result = safeToEval && settings.allowNativeEval ? eval(input) : fallback(input);
```
Prettier will turn the above into:
```js
// eslint-disable-next-line no-eval
const result =
safeToEval && settings.allowNativeEval ? eval(input) : fallback(input);
```
Which means that the `eslint-disable` comment is no longer effective. In this case you need to move the comment:
```js
const result =
// eslint-disable-next-line no-eval
safeToEval && settings.allowNativeEval ? eval(input) : fallback(input);
```
## What Prettier is _not_ concerned about
Prettier only _prints_ code. It does not transform it. This is to limit the scope of Prettier. Let's focus on the printing and do it really well!
Here are a few examples of things that are out of scope for Prettier:
- Turning single- or double-quoted strings into template literals or vice versa.
- Using `+` to break long string literals into parts that fit the print width.
- Adding/removing `{}` and `return` where they are optional.
- Turning `?:` into `if`-`else` statements.
- Sorting/moving imports, object keys, class members, JSX keys, CSS properties or anything else. Apart from being a _transform_ rather than just printing (as mentioned above), sorting is potentially unsafe because of side effects (for imports, as an example) and makes it difficult to verify the most important [correctness](#correctness) goal.

View File

@ -0,0 +1,41 @@
---
id: version-stable-related-projects
title: Related Projects
original_id: related-projects
---
## ESLint Integrations
- [`eslint-plugin-prettier`](https://github.com/prettier/eslint-plugin-prettier) plugs Prettier into your ESLint workflow
- [`eslint-config-prettier`](https://github.com/prettier/eslint-config-prettier) turns off all ESLint rules that are unnecessary or might conflict with Prettier
- [`prettier-eslint`](https://github.com/prettier/prettier-eslint) passes `prettier` output to `eslint --fix`
- [`prettier-standard`](https://github.com/sheerun/prettier-standard) uses `prettier` and `prettier-eslint` to format code with standard rules
- [`prettier-standard-formatter`](https://github.com/dtinth/prettier-standard-formatter) passes `prettier` output to `standard --fix`
## TSLint Integrations
- [`tslint-plugin-prettier`](https://github.com/ikatyang/tslint-plugin-prettier) runs Prettier as a TSLint rule and reports differences as individual TSLint issues
- [`tslint-config-prettier`](https://github.com/alexjoverm/tslint-config-prettier) use TSLint with Prettier without any conflict
- [`prettier-tslint`](https://github.com/azz/prettier-tslint) passes `prettier` output to `tslint --fix`
## stylelint Integrations
- [`stylelint-prettier`](https://github.com/prettier/stylelint-prettier) runs Prettier as a stylelint rule and reports differences as individual stylelint issues
- [`stylelint-config-prettier`](https://github.com/prettier/stylelint-config-prettier) turns off all rules that are unnecessary or might conflict with Prettier.
- [`prettier-stylelint`](https://github.com/hugomrdias/prettier-stylelint) passes `prettier` output to `stylelint --fix`
## Forks
- [`prettier-miscellaneous`](https://github.com/arijs/prettier-miscellaneous) `prettier` with a few minor extra options
## Misc
- [`neutrino-preset-prettier`](https://github.com/SpencerCDixon/neutrino-preset-prettier) allows you to use Prettier as a Neutrino preset
- [`prettier_d`](https://github.com/josephfrazier/prettier_d.js) runs Prettier as a server to avoid Node.js startup delay. It also supports configuration via `.prettierrc`, `package.json`, and `.editorconfig`.
- [`Prettier Bookmarklet`](https://prettier.glitch.me/) provides a bookmarklet and exposes a REST API for Prettier that allows to format CodeMirror editor in your browser
- [`prettier-github`](https://github.com/jgierer12/prettier-github) formats code in GitHub comments
- [`rollup-plugin-prettier`](https://github.com/mjeanroy/rollup-plugin-prettier) allows you to use Prettier with Rollup
- [`markdown-magic-prettier`](https://github.com/camacho/markdown-magic-prettier) allows you to use Prettier to format JS [codeblocks](https://help.github.com/articles/creating-and-highlighting-code-blocks/) in Markdown files via [Markdown Magic](https://github.com/DavidWells/markdown-magic)
- [`pretty-quick`](https://github.com/azz/pretty-quick) formats your changed files with Prettier
- [`prettier-chrome`](https://github.com/u3u/prettier-chrome) an extension that can be formatted using Prettier in Chrome
- [`prettylint`](https://github.com/ikatyang/prettylint) run Prettier as a linter

View File

@ -0,0 +1,13 @@
---
id: version-stable-technical-details
title: Technical Details
original_id: technical-details
---
This printer is a fork of [recast](https://github.com/benjamn/recast)'s printer with its algorithm replaced by the one described by Wadler in "[A prettier printer](http://homepages.inf.ed.ac.uk/wadler/papers/prettier/prettier.pdf)". There still may be leftover code from recast that needs to be cleaned up.
The basic idea is that the printer takes an AST and returns an intermediate representation of the output, and the printer uses that to generate a string. The advantage is that the printer can "measure" the IR and see if the output is going to fit on a line, and break if not.
This means that most of the logic of printing an AST involves generating an abstract representation of the output involving certain commands. For example, `concat(["(", line, arg, line ")"])` would represent a concatenation of opening parens, an argument, and closing parens. But if that doesn't fit on one line, the printer can break where `line` is specified.
More (rough) details can be found in [commands.md](https://github.com/prettier/prettier/blob/master/commands.md).

View File

@ -0,0 +1,134 @@
---
id: version-stable-vim
title: Vim Setup
original_id: vim
---
Vim users can install either [vim-prettier](https://github.com/prettier/vim-prettier), which is Prettier specific, or [Neoformat](https://github.com/sbdchd/neoformat) or [ALE](https://github.com/w0rp/ale) which are generalized lint/format engines with support for Prettier.
## [vim-prettier](https://github.com/prettier/vim-prettier)
See the [vim-prettier](https://github.com/prettier/vim-prettier) readme for installation and usage instructions.
## [Neoformat](https://github.com/sbdchd/neoformat)
The best way to install Neoformat is with your favorite plugin manager for Vim, such as [vim-plug](https://github.com/junegunn/vim-plug):
```
Plug 'sbdchd/neoformat'
```
Run `:Neoformat` or `:Neoformat prettier` in a supported file to run Prettier.
To have Neoformat run Prettier on save:
```
autocmd BufWritePre *.js Neoformat
```
You can also make Vim format your code more frequently, by setting an `autocmd` for other events. Here are a couple of useful ones:
- `TextChanged`: after a change was made to the text in Normal mode
- `InsertLeave`: when leaving Insert mode
For example, you can format on both of the above events together with `BufWritePre` like this:
```
autocmd BufWritePre,TextChanged,InsertLeave *.js Neoformat
```
See `:help autocmd-events` in Vim for details.
It's recommended to use a [config file](configuration.md), but you can also add options in your `.vimrc`:
```
autocmd FileType javascript setlocal formatprg=prettier\ --stdin\ --single-quote\ --trailing-comma\ es5
" Use formatprg when available
let g:neoformat_try_formatprg = 1
```
Each space in prettier options should be escaped with `\`.
## [ALE](https://github.com/w0rp/ale)
ALE requires either Vim 8 or Neovim as ALE makes use of the asynchronous abilities that both Vim 8 and Neovim provide.
The best way to install ALE is with your favorite plugin manager for Vim, such as [vim-plug](https://github.com/junegunn/vim-plug):
```
Plug 'w0rp/ale'
```
You can find further instructions on the [ALE repository](https://github.com/w0rp/ale#3-installation).
ALE will try to use Prettier installed locally before looking for a global installation.
Enable the Prettier fixer for the languages you use:
```
let g:ale_fixers = {
\ 'javascript': ['prettier'],
\ 'css': ['prettier'],
\}
```
ALE supports both _linters_ and _fixers_. If you don't specify which _linters_ to run, **all available tools for all supported languages will be run**, and you might get a correctly formatted file with a bunch of lint errors. To disable this behavior you can tell ALE to run only linters you've explicitly configured (more info in the [FAQ](https://github.com/w0rp/ale/blob/ed8104b6ab10f63c78e49b60d2468ae2656250e9/README.md#faq-disable-linters)):
```
let g:ale_linters_explicit = 1
```
You can then run `:ALEFix` in a JavaScript or CSS file to run Prettier.
To have ALE run Prettier on save:
```
let g:ale_fix_on_save = 1
```
It's recommended to use a [config file](configuration.md), but you can also add options in your `.vimrc`:
```
let g:ale_javascript_prettier_options = '--single-quote --trailing-comma es5'
```
## [coc-prettier](https://github.com/neoclide/coc-prettier)
Prettier extension for [coc.nvim](https://github.com/neoclide/coc.nvim) which requires neovim or vim8.1.
Install coc.nvim with your favorite plugin manager, such as [vim-plug](https://github.com/junegunn/vim-plug):
```
Plug 'neoclide/coc.nvim', {'do': { -> coc#util#install()}}
```
And install coc-prettier by command:
```
CocInstall coc-prettier
```
Setup `Prettier` command in your `init.vim` or `.vimrc`
```
command! -nargs=0 Prettier :call CocAction('runCommand', 'prettier.formatFile')
```
Update your `coc-settings.json` for languages that you want format on save.
```
"coc.preferences.formatOnSaveFiletypes": ["css", "Markdown"],
```
[coc-prettier](https://github.com/neoclide/coc-prettier) have same configurations of [prettier-vscode](https://github.com/prettier/prettier-vscode), open `coc-settings.json` by `:CocConfig` to get autocompletion support.
## Running manually
If you want something really bare-bones, you can create a custom key binding. In this example, `gp` (mnemonic: "get pretty") is used to run prettier (with options) in the currently active buffer:
```
nnoremap gp :silent %!prettier --stdin --stdin-filepath % --trailing-comma all --single-quote<CR>
```
Note that if there's a syntax error in your code, the whole buffer will be replaced with an error message. You'll need to press `u` to get your code back.
Another disadvantage of this approach is that the cursor position won't be preserved.

View File

@ -0,0 +1,19 @@
---
id: version-stable-watching-files
title: Watching For Changes
original_id: watching-files
---
If you prefer to have prettier watch for changes from the command line you can use a package like [onchange](https://www.npmjs.com/package/onchange). For example:
```
npx onchange '**/*.js' -- npx prettier --write {{changed}}
```
or add the following to your `package.json`
```json
"scripts": {
"prettier-watch": "onchange '**/*.js' -- prettier --write {{changed}}"
},
```

View File

@ -0,0 +1,62 @@
---
id: version-stable-webstorm
title: WebStorm Setup
original_id: webstorm
---
## WebStorm 2018.1 and above
Use the `Reformat with Prettier` action (`Alt-Shift-Cmd-P` on macOS or `Alt-Shift-Ctrl-P` on Windows and Linux) to format the selected code, a file, or a whole directory.
Don't forget to install `prettier` first.
To use Prettier in IntelliJ IDEA, PhpStorm, PyCharm, and other JetBrains IDEs, please install this [plugin](https://plugins.jetbrains.com/plugin/10456-prettier).
For older IDE versions, please follow the instructions below.
## Running Prettier on save using File Watcher
To automatically format your files using `prettier` on save, you can use a [File Watcher](https://plugins.jetbrains.com/plugin/7177-file-watchers).
Go to _Preferences | Tools | File Watchers_ and click **+** to add a new watcher.
In Webstorm 2018.2, select Prettier from the list, review the configuration, add any additional arguments if needed, and click OK.
In older IDE versions, select Custom and do the following configuration:
- **Name**: _Prettier_ or any other name
- **File Type**: _JavaScript_ (or _Any_ if you want to run `prettier` on all files)
- **Scope**: _Project Files_
- **Program**: full path to `.bin/prettier` or `.bin\prettier.cmd` in the project's `node_module` folder. Or, if Prettier is installed globally, select `prettier` on macOS and Linux or `C:\Users\user_name\AppData\Roaming\npm\prettier.cmd` on Windows (or whatever `npm prefix -g` returns).
- **Arguments**: `--write [other options] $FilePathRelativeToProjectRoot$`
- **Output paths to refresh**: `$FilePathRelativeToProjectRoot$`
- **Working directory**: `$ProjectFileDir$`
- **Auto-save edited files to trigger the watcher**: Uncheck to reformat on Save only.
![Example](/docs/assets/webstorm/file-watcher-prettier.png)
## WebStorm 2017.3 or earlier
### Using Prettier with ESLint
If you are using ESLint with [eslint-plugin-prettier](https://github.com/prettier/eslint-plugin-prettier), use the `Fix ESLint Problems` action to reformat the currect file find it using _Find Action_ (`Cmd/Ctrl-Shift-A`) or [add a keyboard shortcut](https://www.jetbrains.com/help/webstorm/configuring-keyboard-shortcuts.html) to it in _Preferences | Keymap_ and then use it.
Make sure that the ESLint integration is enabled in _Preferences | Languages & Frameworks | JavaScript | Code Quality Tools | ESLint_.
### Using Prettier as External Tool
Go to _Preferences | Tools | External Tools_ and click **+** to add a new tool. Lets name it **Prettier**.
- **Program**: `prettier` on macOS and Linux or `C:\Users\user_name\AppData\Roaming\npm\prettier.cmd` on Windows (or whatever `npm prefix -g` returns), if Prettier is installed globally
- **Parameters**: `--write [other options] $FilePathRelativeToProjectRoot$`
- **Working directory**: `$ProjectFileDir$`
> If Prettier is installed locally in your project, replace the path in **Program** with `$ProjectFileDir$/node_modules/.bin/prettier` on macOS and Linux or `$ProjectFileDir$\node_modules\.bin\prettier.cmd` on Windows.
![Example](/docs/assets/webstorm/external-tool-prettier.png)
Press `Cmd/Ctrl-Shift-A` (_Find Action_), search for _Prettier_, and then hit `Enter`.
It will run `prettier` for the current file.
You can [add a keyboard shortcut](https://www.jetbrains.com/help/webstorm/configuring-keyboard-shortcuts.html) to run this External tool configuration in _Preferences | Keymap_.

View File

@ -0,0 +1,62 @@
---
id: version-stable-why-prettier
title: Why Prettier?
original_id: why-prettier
---
## Building and enforcing a style guide
By far the biggest reason for adopting Prettier is to stop all the on-going debates over styles. [It is generally accepted that having a common style guide is valuable for a project and team](https://www.smashingmagazine.com/2012/10/why-coding-style-matters/) but getting there is a very painful and unrewarding process. People get very emotional around particular ways of writing code and nobody likes spending time writing and receiving nits.
So why choose the "Prettier style guide" over any other random style guide? Because Prettier is the only "style guide" that is fully automatic. Even if Prettier does not format all code 100% the way you'd like, it's worth the "sacrifice" given the unique benefits of Prettier, don't you think?
- “We want to free mental threads and end discussions around style. While sometimes fruitful, these discussions are for the most part wasteful.”
- “Literally had an engineer go through a huge effort of cleaning up all of our code because we were debating ternary style for the longest time and were inconsistent about it. It was dumb, but it was a weird on-going "great debate" that wasted lots of little back and forth bits. It's far easier for us all to agree now: just run Prettier, and go with that style.”
- “Getting tired telling people how to style their product code.”
- “Our top reason was to stop wasting our time debating style nits.”
- “Having a githook set up has reduced the amount of style issues in PRs that result in broken builds due to ESLint rules or things I have to nit-pick or clean up later.”
- “I don't want anybody to nitpick any other person ever again.”
- “It reminds me of how Steve Jobs used to wear the same clothes every day because he has a million decisions to make and he didn't want to be bothered to make trivial ones like picking out clothes. I think Prettier is like that.”
## Helping Newcomers
Prettier is usually introduced by people with experience in the current codebase and JavaScript but the people that disproportionally benefit from it are newcomers to the codebase. One may think that it's only useful for people with very limited programming experience, but we've seen it quicken the ramp up time from experienced engineers joining the company, as they likely used a different coding style before, and developers coming from a different programming language.
- “My motivations for using Prettier are: appearing that I know how to write JavaScript well.”
- “I always put spaces in the wrong place, now I don't have to worry about it anymore.”
- “When you're a beginner you're making a lot of mistakes caused by the syntax. Thanks to Prettier, you can reduce these mistakes and save a lot of time to focus on what really matters.”
- “As a teacher, I will also tell to my students to install Prettier to help them to learn the JS syntax and have readable files.”
## Writing code
What usually happens once people are using Prettier is that they realize that they actually spend a lot of time and mental energy formatting their code. With Prettier editor integration, you can just press that magic key binding and poof, the code is formatted. This is an eye opening experience if anything else.
- “I want to write code. Not spend cycles on formatting.”
- “It removed 5% that sucks in our daily life - aka formatting”
- “We're in 2017 and it's still painful to break a call into multiple lines when you happen to add an argument that makes it go over the 80 columns limit :(“
## Easy to adopt
We've worked very hard to use the least controversial coding styles, went through many rounds of fixing all the edge cases and polished the getting started experience. When you're ready to push Prettier into your codebase, not only should it be painless for you to do it technically but the newly formatted codebase should not generate major controversy and be accepted painlessly by your co-workers.
- “It's low overhead. We were able to throw Prettier at very different kinds of repos without much work.”
- “It's been mostly bug free. Had there been major styling issues during the course of implementation we would have been wary about throwing this at our JS codebase. I'm happy to say that's not the case.”
- “Everyone runs it as part of their pre commit scripts, a couple of us use the editor on save extensions as well.”
- “It's fast, against one of our larger JS codebases we were able to run Prettier in under 13 seconds.”
- “The biggest benefit for Prettier for us was being able to format the entire code base at once.”
## Clean up an existing codebase
Since coming up with a coding style and enforcing it is a big undertaking, it often slips through the cracks and you are left working on inconsistent codebases. Running Prettier in this case is a quick win, the codebase is now uniform and easier to read without spending hardly any time.
- “Take a look at the code :) I just need to restore sanity.”
- “We inherited a ~2000 module ES6 code base, developed by 20 different developers over 18 months, in a global team. Felt like such a win without much research.”
## Ride the hype train
Purely technical aspects of the projects aren't the only thing people look into when choosing to adopt Prettier. Who built and uses it and how quickly it spreads through the community has a non-trivial impact.
- “The amazing thing, for me, is: 1) Announced 2 months ago. 2) Already adopted by, it seems, every major JS project. 3) 7000 stars, 100,000 npm downloads/mo”
- “Was built by the same people as React & React Native.”
- “I like to be part of the hot new things.”
- “Because soon enough people are gonna ask for it.”

View File

@ -0,0 +1,35 @@
{
"version-stable-docs": {
"About": [
"version-stable-index",
"version-stable-why-prettier",
"version-stable-comparison",
"version-stable-option-philosophy",
"version-stable-rationale"
],
"Usage": [
"version-stable-install",
"version-stable-cli",
"version-stable-api",
"version-stable-browser",
"version-stable-plugins",
"version-stable-precommit",
"version-stable-watching-files",
"version-stable-eslint",
"version-stable-ignore"
],
"Configuring Prettier": [
"version-stable-options",
"version-stable-configuration"
],
"Editors": [
"version-stable-editors",
"version-stable-webstorm",
"version-stable-vim"
],
"Misc": [
"version-stable-technical-details",
"version-stable-related-projects"
]
}
}

3
website/versions.json Normal file
View File

@ -0,0 +1,3 @@
[
"stable"
]

File diff suppressed because it is too large Load Diff