From ca437912cc42808601b8d251ba92034461ee9820 Mon Sep 17 00:00:00 2001 From: Simon Lydell Date: Wed, 1 Jul 2020 08:44:21 +0200 Subject: [PATCH] Update stable docs (#8652) --- docs/precommit.md | 2 +- docs/rationale.md | 2 +- docs/vim.md | 2 +- website/versioned_docs/version-stable/api.md | 22 ++- .../versioned_docs/version-stable/browser.md | 8 +- website/versioned_docs/version-stable/cli.md | 38 ++-- .../version-stable/comparison.md | 4 +- .../version-stable/configuration.md | 21 +- .../versioned_docs/version-stable/editors.md | 46 +++-- .../versioned_docs/version-stable/ignore.md | 33 +++- .../versioned_docs/version-stable/index.md | 8 +- .../versioned_docs/version-stable/install.md | 123 ++++++++++-- .../integrating-with-linters.md | 180 +++--------------- .../versioned_docs/version-stable/options.md | 28 ++- .../versioned_docs/version-stable/plugins.md | 13 +- .../version-stable/precommit.md | 65 +++++-- .../version-stable/rationale.md | 36 ++-- .../version-stable/related-projects.md | 44 ++--- .../version-stable/technical-details.md | 4 +- website/versioned_docs/version-stable/vim.md | 18 +- .../version-stable/watching-files.md | 4 +- .../versioned_docs/version-stable/webstorm.md | 12 +- .../version-stable/why-prettier.md | 22 +-- .../version-stable-sidebars.json | 14 +- 24 files changed, 398 insertions(+), 351 deletions(-) diff --git a/docs/precommit.md b/docs/precommit.md index 34bd9560b..9c488d5ef 100644 --- a/docs/precommit.md +++ b/docs/precommit.md @@ -154,7 +154,7 @@ Alternately you can save this script as `.git/hooks/pre-commit` and give it exec ```sh #!/bin/sh -FILES=$(git diff --cached --name-only --diff-filter=ACMR "*.js" "*.jsx" | sed ’s| |\\ |g') +FILES=$(git diff --cached --name-only --diff-filter=ACMR "*.js" "*.jsx" | sed 's| |\\ |g') [ -z "$FILES" ] && exit 0 # Prettify all selected files diff --git a/docs/rationale.md b/docs/rationale.md index 5faae3a04..94752bb18 100644 --- a/docs/rationale.md +++ b/docs/rationale.md @@ -266,7 +266,7 @@ When it comes to the _content_ of comments, Prettier can’t do much really. Com Then there’s the question of _where_ to put the comments. Turns out this is a really difficult problem. Prettier tries its best to keep your comments roughly where they were, but it’s 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`. +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. diff --git a/docs/vim.md b/docs/vim.md index 6d5fdd771..70eb9efdf 100644 --- a/docs/vim.md +++ b/docs/vim.md @@ -71,7 +71,7 @@ let g:ale_fixers = { \} ``` -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/dense-analysis/ale/blob/ed8104b6ab10f63c78e49b60d2468ae2656250e9/README.md#faq-disable-linters)): +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/dense-analysis/ale/blob/ed8104b6ab10f63c78e49b60d2468ae2656250e9/README.md#faq-disable-linters)): ```vim let g:ale_linters_explicit = 1 diff --git a/website/versioned_docs/version-stable/api.md b/website/versioned_docs/version-stable/api.md index ef89f7e24..73f2b3a89 100644 --- a/website/versioned_docs/version-stable/api.md +++ b/website/versioned_docs/version-stable/api.md @@ -4,6 +4,8 @@ title: API original_id: api --- +If you want to run Prettier programmatically, check this page out. + ```js const prettier = require("prettier"); ``` @@ -34,7 +36,7 @@ prettier.formatWithCursor(" 1", { cursorOffset: 2, parser: "babel" }); ## `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: +`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. @@ -50,14 +52,14 @@ prettier.resolveConfig(filePath).then((options) => { }); ``` -If `options.editorconfig` is `true` and an [`.editorconfig` file](https://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: +If `options.editorconfig` is `true` and an [`.editorconfig` file](https://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. +Use `prettier.resolveConfig.sync(filePath [, options])` if you’d like to use sync version. ## `prettier.resolveConfigFile([filePath])` @@ -71,14 +73,12 @@ The promise will be rejected if there was an error parsing the configuration fil The search starts at `process.cwd()`, or at `filePath` if provided. Please see the [cosmiconfig docs](https://github.com/davidtheclark/cosmiconfig#explorersearch) for details on how the resolving works. ```js -prettier.resolveConfigFile().then((filePath) => { - prettier.resolveConfig(filePath).then((options) => { - const formatted = prettier.format(text, options); - }); +prettier.resolveConfigFile(filePath).then((configFile) => { + // you got the path of the configuration file }); ``` -Use `prettier.resolveConfigFile.sync([filePath])` if you'd like to use sync version. +Use `prettier.resolveConfigFile.sync([filePath])` if you’d like to use sync version. ## `prettier.clearConfigCache()` @@ -99,11 +99,13 @@ The promise will be rejected if the type of `filePath` is not `string`. Setting `options.ignorePath` (`string`) and `options.withNodeModules` (`boolean`) influence the value of `ignored` (`false` by default). +If the given `filePath` is ignored, the `inferredParser` is always `null`. + Providing [plugin](plugins.md) paths in `options.plugins` (`string[]`) helps extract `inferredParser` for files that are not supported by Prettier core. When setting `options.resolveConfig` (`boolean`, default `false`), Prettier will resolve the configuration for the given `filePath`. This is useful, for example, when the `inferredParser` might be overridden for a subset of files. -Use `prettier.getFileInfo.sync(filePath [, options])` if you'd like to use sync version. +Use `prettier.getFileInfo.sync(filePath [, options])` if you’d like to use sync version. ## `prettier.getSupportInfo()` @@ -139,7 +141,7 @@ If you need to make modifications to the AST (such as codemods), or you want to (text: string, parsers: object, options: object) => AST; ``` -Prettier's built-in parsers are exposed as properties on the `parsers` argument. +Prettier’s built-in parsers are exposed as properties on the `parsers` argument. ```js prettier.format("lodash ( )", { diff --git a/website/versioned_docs/version-stable/browser.md b/website/versioned_docs/version-stable/browser.md index e0619ef1c..b0279dc69 100644 --- a/website/versioned_docs/version-stable/browser.md +++ b/website/versioned_docs/version-stable/browser.md @@ -6,9 +6,11 @@ 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 UMD bundle only formats the code and has no support for config files, ignore files, CLI usage, or automatic loading of plugins. +The [`browser` field](https://github.com/defunctzombie/package-browser-field-spec) in Prettier’s `package.json` points to `standalone.js`. That’s why you can just `import` or `require` the `prettier` module to access Prettier’s API, and your code can stay compatible with both Node and the browser as long as webpack or another bundler that supports the `browser` field is used. This is especially convenient for [plugins](plugins.md). + ### `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. +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. @@ -27,6 +29,8 @@ See [Usage](#usage) below for examples. ``` +Note that the [`unpkg` field](https://unpkg.com/#examples) in Prettier’s `package.json` points to `standalone.js`, that’s why `https://unpkg.com/prettier` can also be used instead of `https://unpkg.com/prettier/standalone.js`. + ### ES Modules ```js @@ -58,7 +62,7 @@ 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. +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 diff --git a/website/versioned_docs/version-stable/cli.md b/website/versioned_docs/version-stable/cli.md index 5f5e6959e..3206769fc 100644 --- a/website/versioned_docs/version-stable/cli.md +++ b/website/versioned_docs/version-stable/cli.md @@ -4,14 +4,16 @@ title: CLI original_id: cli --- -Use the `prettier` command to run Prettier from the command line. 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. +Use the `prettier` command to run Prettier from the command line. ```bash prettier [options] [file/dir/glob ...] ``` +> To run your locally installed version of Prettier, prefix the command with `npx` or `yarn` (if you use Yarn), i.e. `npx prettier --help`, or `yarn prettier --help`. + +To format a file in-place, use `--write`. (Note: This overwrites your files!) + In practice, this may look something like: ```bash @@ -20,19 +22,23 @@ prettier --write . This command formats all files supported by Prettier in the current directory and its subdirectories. +It’s recommended to always make sure that `prettier --write .` only formats what you want in your project. Use a [.prettierignore](ignore.md) file to ignore things that should not be formatted. + A more complicated example: ```bash prettier --single-quote --trailing-comma all --write docs package.json "{app,__{tests,mocks}__}/**/*.js" ``` -> Don't forget the **quotes** around the globs! The quotes make sure that Prettier CLI expands the globs rather than your shell, which is important for cross-platform usage. +> Don’t forget the **quotes** around the globs! The quotes make sure that Prettier CLI expands the globs rather than your shell, which is important for cross-platform usage. -> It's usually better to use a [configuration file](configuration.md) for formatting options like `--single-quote` and `--trailing-comma` instead of passing them as CLI flags. This allows sharing those settings across different ways to run Prettier (CLI, [editor integrations](editors.md), etc.). +> It’s better to use a [configuration file](configuration.md) for formatting options like `--single-quote` and `--trailing-comma` instead of passing them as CLI flags. This way the Prettier CLI, [editor integrations](editors.md), and other tooling can all know what options you use. -Given a list of paths/patterns, Prettier CLI first treats every entry in it as a literal path. +## File patterns -- If the path points to an existing file, Prettier CLI proceeds with that file and doesn't resolve the path as a glob pattern. +Given a list of paths/patterns, the Prettier CLI first treats every entry in it as a literal path. + +- If the path points to an existing file, Prettier CLI proceeds with that file and doesn’t resolve the path as a glob pattern. - If the path points to an existing directory, Prettier CLI recursively finds supported files in that directory. This resolution process is based on file extensions and well-known file names that Prettier and its [plugins](plugins.md) associate with supported languages. @@ -40,7 +46,7 @@ Given a list of paths/patterns, Prettier CLI first treats every entry in it as a Prettier CLI will ignore files located in `node_modules` directory. To opt out from this behavior use `--with-node-modules` flag. -To escape special characters in globs, one of the two escaping syntaxes can be used: `prettier "\[my-dir]/*.js"` or `prettier "[[]my-dir]/*.js"`. Both match all JS files in a directory named `[my-dir]`, however the latter syntax is preferable as the former doesn't work on Windows, where backslashes are treated as path separators. +To escape special characters in globs, one of the two escaping syntaxes can be used: `prettier "\[my-dir]/*.js"` or `prettier "[[]my-dir]/*.js"`. Both match all JS files in a directory named `[my-dir]`, however the latter syntax is preferable as the former doesn’t work on Windows, where backslashes are treated as path separators. ## `--check` @@ -79,8 +85,8 @@ If you need to pipe the list of unformatted files to another command, you can u | Code | Information | | ---- | ----------------------------------- | | 0 | Everything formatted properly | -| 1 | Something wasn't formatted properly | -| 2 | Something's wrong with Prettier | +| 1 | Something wasn’t formatted properly | +| 2 | Something’s wrong with Prettier | ## `--debug-check` @@ -88,7 +94,7 @@ If you're worried that Prettier will change the correctness of your code, add `- ## `--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. +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 @@ -101,17 +107,17 @@ This will provide you with a path to the configuration file, which you can pass 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. +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. +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`. +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. +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 /** @@ -159,7 +165,7 @@ This option adds support to editor integrations where users define their default ## `--no-editorconfig` -Don't take .editorconfig into account when parsing configuration. See the [`prettier.resolveConfig` docs](api.md) for details. +Don’t take .editorconfig into account when parsing configuration. See the [`prettier.resolveConfig` docs](api.md) for details. ## `--with-node-modules` diff --git a/website/versioned_docs/version-stable/comparison.md b/website/versioned_docs/version-stable/comparison.md index b22ca7b16..566b8aa53 100644 --- a/website/versioned_docs/version-stable/comparison.md +++ b/website/versioned_docs/version-stable/comparison.md @@ -10,8 +10,10 @@ Linters have two categories of rules: **Formatting rules**: eg: [max-len](https://eslint.org/docs/rules/max-len), [no-mixed-spaces-and-tabs](https://eslint.org/docs/rules/no-mixed-spaces-and-tabs), [keyword-spacing](https://eslint.org/docs/rules/keyword-spacing), [comma-style](https://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 :) +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](https://eslint.org/docs/rules/no-unused-vars), [no-extra-bind](https://eslint.org/docs/rules/no-extra-bind), [no-implicit-globals](https://eslint.org/docs/rules/no-implicit-globals), [prefer-promise-reject-errors](https://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! + +In other words, use **Prettier for formatting** and **linters for catching bugs!** diff --git a/website/versioned_docs/version-stable/configuration.md b/website/versioned_docs/version-stable/configuration.md index e4cc8fc8a..3bc8f3f15 100644 --- a/website/versioned_docs/version-stable/configuration.md +++ b/website/versioned_docs/version-stable/configuration.md @@ -4,16 +4,19 @@ 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 (in order of precedence): +Prettier uses [cosmiconfig](https://github.com/davidtheclark/cosmiconfig) for configuration file support. This means you can configure Prettier via (in order of precedence): - A `"prettier"` key in your `package.json` file. -- A `.prettierrc` file, written in JSON or YAML, with optional extensions: `.json/.yaml/.yml` (without extension takes precedence). -- A `.prettierrc.js` or `prettier.config.js` file that exports an object. -- A `.prettierrc.toml` file, written in TOML (the `.toml` extension is _required_). +- A `.prettierrc` file written in JSON or YAML. +- A `.prettierrc.json`, `.prettierrc.yml`, or `.prettierrc.yaml` file. +- A `.prettierrc.js` or `prettier.config.js` file that exports an object using `module.exports`. +- A `.prettierrc.toml` 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 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). +Prettier intentionally doesn’t support any kind of global configuration. This is to make sure that when a project is copied to another computer, Prettier’s behavior stays the same. Otherwise, Prettier wouldn’t be able to guarantee that everybody in a team gets the same consistent results. + +The options you can use in the configuration file are the same as the [API options](options.md). ## Basic Configuration @@ -117,7 +120,7 @@ Sharing a Prettier configuration is simple: just publish a module that exports a } ``` -If you don't want to use `package.json`, you can use any of the supported extensions to export a string, e.g. `.prettierrc.json`: +If you don’t want to use `package.json`, you can use any of the supported extensions to export a string, e.g. `.prettierrc.json`: ```json "@company/prettier-config" @@ -166,8 +169,8 @@ You can also switch to the `flow` parser instead of the default `babel` for .js } ``` -**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. +**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. +If you’d like a JSON schema to validate your configuration, one is available here: http://json.schemastore.org/prettierrc. diff --git a/website/versioned_docs/version-stable/editors.md b/website/versioned_docs/version-stable/editors.md index ca7166fda..ef83b5df6 100644 --- a/website/versioned_docs/version-stable/editors.md +++ b/website/versioned_docs/version-stable/editors.md @@ -4,34 +4,27 @@ title: Editor Integration original_id: editors --- -## Atom +To get the most out of Prettier, it’s recommended to run it from your editor. -Atom users can simply install the [prettier-atom] package and use `Ctrl+Alt+F` to format a file (or format on save if enabled). +If your editor does not support Prettier, you can instead [run Prettier with a file watcher](watching-files.md). -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). +**Note!** It’s important to [install](install.md) Prettier locally in every project, so each project gets the correct Prettier version. ## 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 esbenp.prettier-vscode` in the command palette. [Check its repository for configuration and shortcuts](https://github.com/prettier/prettier-vscode). +`prettier-vscode` can be installed using the extension sidebar – it’s called “Prettier - Code formatter.” [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). +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 +## Emacs -Install the [JavaScript Prettier extension](https://github.com/madskristensen/JavaScriptPrettier). +Check out the [prettier-emacs](https://github.com/prettier/prettier-emacs) repo, or [prettier.el](https://github.com/jscheid/prettier.el). + +## Vim + +[vim-prettier](https://github.com/prettier/vim-prettier) is a Prettier-specific Vim plugin. [Neoformat](https://github.com/sbdchd/neoformat), [ALE](https://github.com/w0rp/ale), and [coc-prettier](https://github.com/neoclide/coc-prettier) are multi-language Vim linter/formatter plugins that support Prettier. + +For more details see [the Vim setup guide](vim.md). ## Sublime Text @@ -41,4 +34,15 @@ Sublime Text support is available through Package Control and the [JsPrettier](h See the [WebStorm setup guide](webstorm.md). -[prettier-atom]: https://github.com/prettier/prettier-atom +## Visual Studio + +Install the [JavaScript Prettier extension](https://github.com/madskristensen/JavaScriptPrettier). + +## Atom + +Atom users can install the [prettier-atom](https://github.com/prettier/prettier-atom) package, or one of the more minimalistic [mprettier](https://github.com/t9md/atom-mprettier) and +[miniprettier](https://github.com/duailibe/atom-miniprettier) packages. + +## Espresso + +Espresso users can install the [espresso-prettier](https://github.com/eablokker/espresso-prettier) plugin. diff --git a/website/versioned_docs/version-stable/ignore.md b/website/versioned_docs/version-stable/ignore.md index 527b3fddc..c97924ed0 100644 --- a/website/versioned_docs/version-stable/ignore.md +++ b/website/versioned_docs/version-stable/ignore.md @@ -4,11 +4,28 @@ title: Ignoring Code original_id: ignore --- -Prettier offers an escape hatch to ignore a block of code or prevent entire files from being formatted. +Use `.prettierignore` to ignore (i.e. not reformat) certain files and folders completely. -## Ignoring Files +Use “prettier-ignore” comments to ignore parts of 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). `.prettierignore` uses [gitignore syntax](https://git-scm.com/docs/gitignore#_pattern_format). +## Ignoring Files: .prettierignore + +To exclude files from formatting, create a `.prettierignore` file in the root of your project. `.prettierignore` uses [gitignore syntax](https://git-scm.com/docs/gitignore#_pattern_format). + +Example: + +``` +# Ignore artifacts: +build +coverage + +# Ignore all HTML files: +*.html +``` + +It’s recommended to have a `.prettierignore` in your project! This way you can run `prettier --write .` to make sure that everything is formatted (without mangling files you don’t want, or choking on generated files). And – your editor will know which files _not_ to format! + +(See also the [`--ignore-path` CLI option](cli.md#--ignore-path).) ## JavaScript @@ -108,6 +125,16 @@ This type of ignore is only allowed to be used in top-level and aimed to disable ``` +## YAML + +To ignore a part of a YAML file, `# prettier-ignore` should be placed on the line immediately above the ignored node: + +```yaml +# prettier-ignore +key : value +hello: world +``` + ## GraphQL ```graphql diff --git a/website/versioned_docs/version-stable/index.md b/website/versioned_docs/version-stable/index.md index c373e77e5..777151fe0 100644 --- a/website/versioned_docs/version-stable/index.md +++ b/website/versioned_docs/version-stable/index.md @@ -6,7 +6,7 @@ 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) +- JavaScript (including experimental features) - [JSX](https://facebook.github.io/jsx/) - [Angular](https://angular.io/) - [Vue](https://vuejs.org/) @@ -14,7 +14,7 @@ Prettier is an opinionated code formatter with support for: - [TypeScript](https://www.typescriptlang.org/) - CSS, [Less](http://lesscss.org/), and [SCSS](https://sass-lang.com) - [HTML](https://en.wikipedia.org/wiki/HTML) -- [JSON](http://json.org/) +- [JSON](https://json.org/) - [GraphQL](https://graphql.org/) - [Markdown](https://commonmark.org/), including [GFM](https://github.github.com/gfm/) and [MDX](https://mdxjs.com/) - [YAML](https://yaml.org/) @@ -29,7 +29,7 @@ For example, take the following code: 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: +It fits in a single line so it’s going to stay as is. However, we've all run into this situation: ```js @@ -47,7 +47,7 @@ foo( ); ``` -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. +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: diff --git a/website/versioned_docs/version-stable/install.md b/website/versioned_docs/version-stable/install.md index 755c5b985..69e43292e 100644 --- a/website/versioned_docs/version-stable/install.md +++ b/website/versioned_docs/version-stable/install.md @@ -4,26 +4,121 @@ title: Install original_id: install --- -Install with `yarn`: +First, install Prettier locally: -```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. - -If you use `npx` to run Prettier, the version should be pinned like this: + ```bash -npx prettier@2.0.5 . --write +yarn add --dev --exact prettier ``` + + + +Then, create an empty config file to let editors and other tooling know you are using Prettier: + + + +```bash +echo {}> .prettierrc.json +``` + +Next, create a [.prettierignore](ignore.md) file to let the Prettier CLI and editors know which files to _not_ format. Here’s an example: + +``` +# Ignore artifacts: +build +coverage +``` + +> Tip! Base your .prettierignore on .gitignore and .eslintignore (if you have one). + +> Another tip! If your project isn’t ready to format, say, HTML files yet, add `*.html`. + +Now, format all files with Prettier: + + + + +```bash +npx prettier --write . +``` + +> What is that `npx` thing? `npx` ships with `npm` and lets you run locally installed tools. We’ll leave off the `npx` part for brevity throughout the rest of this file! +> +> Note: If you forget to install Prettier first, `npx` will temporarily download the latest version. That’s not a good idea when using Prettier, because we change how code is formatted in each release! It’s important to have a locked down version of Prettier in your `package.json`. And it’s faster, too. + + + +```bash +yarn prettier --write . +``` + +> What is `yarn` doing at the start? `yarn prettier` runs the locally installed version of Prettier. We’ll leave off the `yarn` part for brevity throughout the rest of this file! + + + +`prettier --write .` is great for formatting everything, but for a big project it might take a little while. You may run `prettier --write app/` to format a certain directory, or `prettier --write app/components/Button.js` to format a certain file. Or use a _glob_ like `prettier --write "app/**/*.test.js"` to format all tests in a directory (see [fast-glob](https://github.com/mrmlnc/fast-glob#pattern-syntax) for supported glob syntax). + +If you have a CI setup, run the following as part of it to make sure that everyone runs Prettier. This avoids merge conflicts and other collaboration issues! + +```bash +prettier --check . +``` + +`--check` is like `--write`, but only checks that files are already formatted, rather than overwriting them. `prettier --write` and `prettier --check` are the most common ways to run Prettier. + +## Set up your editor + +Formatting from the command line is a good way to get started, but you get the most from Prettier by running it from your editor, either via a keyboard shortcut or automatically whenever you save a file. When a line has gotten so long while coding that it won’t fit your screen, just hit a key and watch it magically be wrapped into multiple lines! Or when you paste some code and the indentation gets all messed up, let Prettier fix it up for you without leaving your editor. + +See [Editor Integration](editors.md) for how to set up your editor. If your editor does not support Prettier, you can instead [run Prettier with a file watcher](watching-files.md). + +> **Note:** Don’t skip the regular local install! Editor plugins will pick up your local version of Prettier, making sure you use the correct version in every project. (You wouldn’t want your editor accidentally causing lots of changes because it’s using a newer version of Prettier than your project!) +> +> And being able to run Prettier from the command line is still a good fallback, and needed for CI setups. + +## ESLint (and other linters) + +If you use ESLint, install [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier#installation) to make ESLint and Prettier play nice with each other. It turns off all ESLint rules that are unnecessary or might conflict with Prettier. There’s a similar config for Stylelint: [stylelint-config-prettier](https://github.com/prettier/stylelint-config-prettier) + +(See [Prettier vs. Linters](comparison.md) to learn more about formatting vs linting, [Integrating with Linters](integrating-with-linters.md) for more in-depth information on configuring your linters, and [Related projects](related-projects.md) for even more integration possibilities, if needed.) + +## Git hooks + +In addition to running Prettier from the command line (`prettier --write`), checking formatting in CI, and running Prettier from your editor, many people like to run Prettier as a pre-commit hook as well. This makes sure all your commits are formatted, without having to wait for your CI build to finish. + +For example, you can add the following to your `package.json` to have ESLint and Prettier run before each commit, via [lint-staged](https://github.com/okonet/lint-staged) and [husky](https://github.com/typicode/husky). + +```json +{ + "husky": { + "hooks": { + "pre-commit": "lint-staged" + } + }, + "lint-staged": { + "**/*": ["eslint --fix", "prettier --write"] + } +} +``` + +See [Pre-commit Hook](precommit.md) for more information. + +## Summary + +To summarize, we have learned to: + +- Install an exact version of Prettier locally in your project. This makes sure that everyone in the project gets the exact same version of Prettier. Even a patch release of Prettier can result in slightly different formatting, so you wouldn’t want different team members using different versions and formatting each other’s changes back and forth. +- Add a `.prettierrc.json` to let your editor know that you are using Prettier. +- Add a `.prettierignore` to let your editor know which files _not_ to touch, as well as for being able to run `prettier --write .` to format the entire project (without mangling files you don’t want, or choking on generated files). +- Run `prettier --check .` in CI to make sure that your project stays formatted. +- Run Prettier from your editor for the best experience. +- Use [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) to make Prettier and ESLint play nice together. +- Set up a pre-commit hook to make sure that every commit is formatted. diff --git a/website/versioned_docs/version-stable/integrating-with-linters.md b/website/versioned_docs/version-stable/integrating-with-linters.md index a6b762f5b..20dd5b410 100644 --- a/website/versioned_docs/version-stable/integrating-with-linters.md +++ b/website/versioned_docs/version-stable/integrating-with-linters.md @@ -4,174 +4,38 @@ title: Integrating with Linters original_id: integrating-with-linters --- -Prettier can be integrated into workflows with existing linting tools. -This allows you to use Prettier for code formatting concerns, while letting your linter focus on code-quality concerns as outlined in our [comparison with linters](comparison.md). +Linters usually contain not only code quality rules, but also stylistic rules. Most stylistic rules are unnecessary when using Prettier, but worse – they might conflict with Prettier! Use Prettier for code formatting concerns, and linters for code-quality concerns, as outlined in [Prettier vs. Linters](comparison.md). -Whatever linting tool you wish to integrate with, the steps are broadly similar. -First disable any existing formatting rules in your linter that may conflict with how Prettier wishes to format your code. Then you can either add an extension to your linting tool to format your file with Prettier - so that you only need a single command for format a file, or run your linter then Prettier as separate steps. +Luckily it’s easy to turn off rules that conflict or are unnecessary with Prettier, by using these pre-made configs: -All these instructions assume you have already installed `prettier` in your [`devDependencies`]. +- [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) +- [tslint-config-prettier](https://github.com/alexjoverm/tslint-config-prettier) +- [stylelint-config-prettier](https://github.com/prettier/stylelint-config-prettier) -## ESLint +Check out the above links for instructions on how to install and set things up. -### Disable formatting rules +## Notes -[`eslint-config-prettier`](https://github.com/prettier/eslint-config-prettier) is a config that disables rules that conflict with Prettier. Add it to your [`devDependencies`], then extend from it within your `.eslintrc` configuration. Make sure to put it last in the `extends` array, so it gets the chance to override other configs. +When searching for both Prettier and your linter on the Internet you’ll probably find more related projects. These are **generally not recommended,** but can be useful in certain circumstances. -```bash -yarn add --dev eslint-config-prettier -``` +First, we have plugins that let you run Prettier as if it was a linter rule: -Then in `.eslintrc.json`: +- [eslint-plugin-prettier](https://github.com/prettier/eslint-plugin-prettier) +- [tslint-plugin-prettier](https://github.com/ikatyang/tslint-plugin-prettier) +- [stylelint-prettier](https://github.com/prettier/stylelint-prettier) -```json -{ - "extends": ["prettier"] -} -``` +These plugins were especially useful when Prettier was new. By running Prettier inside your linters, you didn’t have to set up any new infrastructure and you could re-use your editor integrations for the linters. But these days you can run `prettier --check .` and most editors have Prettier support. -### Use ESLint to run Prettier +The downsides of those plugins are: -[`eslint-plugin-prettier`](https://github.com/prettier/eslint-plugin-prettier) is a plugin that adds a rule that formats content using Prettier. Add it to your [`devDependencies`], then enable the plugin and rule. +- You end up with a lot of red squiggly lines in your editor, which gets annoying. Prettier is supposed to make you forget about formatting – and not be in your face about it! +- They are slower than running Prettier directly. +- They’re yet one layer of indirection where things may break. -```bash -yarn add --dev eslint-plugin-prettier -``` +Finally, we have tools that runs `prettier` and then immediately for example `eslint --fix` on files. -Then in `.eslintrc.json`: +- [prettier-eslint](https://github.com/prettier/prettier-eslint) +- [prettier-tslint](https://github.com/azz/prettier-tslint) +- [prettier-stylelint](https://github.com/hugomrdias/prettier-stylelint) -```json -{ - "plugins": ["prettier"], - "rules": { - "prettier/prettier": "error" - } -} -``` - -### Recommended configuration - -`eslint-plugin-prettier` exposes a "recommended" configuration that configures both `eslint-plugin-prettier` and `eslint-config-prettier` in a single step. Add both `eslint-plugin-prettier` and `eslint-config-prettier` as developer dependencies, then extend the recommended config: - -```bash -yarn add --dev eslint-config-prettier eslint-plugin-prettier -``` - -Then in `.eslintrc.json`: - -```json -{ - "extends": ["plugin:prettier/recommended"] -} -``` - -## TSLint - -### Disable formatting rules - -[`tslint-config-prettier`](https://github.com/alexjoverm/tslint-config-prettier) is a config that disables rules that conflict with Prettier. Add it to your [`devDependencies`], then extend from it within your `tslint.json` configuration. Make sure to put it last in the `extends` array, so it gets the chance to override other configs. - -```bash -yarn add --dev tslint-config-prettier -``` - -Then in `tslint.json`: - -```json -{ - "extends": ["tslint-config-prettier"] -} -``` - -### Use TSLint to run Prettier - -[`tslint-plugin-prettier`](https://github.com/ikatyang/tslint-plugin-prettier) is a plugin that adds a rule that formats content using Prettier. Add it to your [`devDependencies`], then enable the plugin and rule. - -```bash -yarn add --dev tslint-plugin-prettier -``` - -Then in `tslint.json`: - -```json -{ - "extends": ["tslint-plugin-prettier"], - "rules": { - "prettier": true - } -} -``` - -### Recommended configuration - -`tslint-plugin-prettier` does not expose a recommended configuration. You should combine the two steps above. Add both `tslint-plugin-prettier` and `tslint-config-prettier` as developer dependencies, then add both sets of config. - -```bash -yarn add --dev tslint-config-prettier tslint-plugin-prettier -``` - -Then in `tslint.json`: - -```json -{ - "extends": ["tslint-plugin-prettier", "tslint-config-prettier"], - "rules": { - "prettier": true - } -} -``` - -## Stylelint - -### Disable formatting rules - -[`stylelint-config-prettier`](https://github.com/prettier/stylelint-config-prettier) is a config that disables rules that conflict with Prettier. Add it to your [`devDependencies`], then extend from it within your `.stylelintrc` configuration. Make sure to put it last in the `extends` array, so it gets the chance to override other configs. - -```bash -yarn add --dev stylelint-config-prettier -``` - -Then in `.stylelintrc`: - -```json -{ - "extends": ["stylelint-config-prettier"] -} -``` - -### Use Stylelint to run Prettier - -[`stylelint-prettier`](https://github.com/prettier/stylelint-prettier) is a plugin that adds a rule that formats content using Prettier. Add it to your [`devDependencies`], then enable the plugin and rule. - -```bash -yarn add --dev stylelint-prettier -``` - -Then in `.stylelintrc`: - -```json -{ - "plugins": ["stylelint-prettier"], - "rules": { - "prettier/prettier": true - } -} -``` - -### Recommended configuration - -`stylelint-prettier` exposes a "recommended" configuration that configures both `stylelint-prettier` and `stylelint-config-prettier` in a single step. Add both `stylelint-prettier` and `stylelint-config-prettier` as developer dependencies, then extend the recommended config: - -```bash -yarn add --dev stylelint-config-prettier stylelint-prettier -``` - -Then in `.stylelintrc`: - -```json -{ - "extends": ["stylelint-prettier/recommended"] -} -``` - -[`devdependencies`]: https://docs.npmjs.com/specifying-dependencies-and-devdependencies-in-a-package-json-file +Those are useful if some aspect of Prettier’s output makes Prettier completely unusable to you. Then you can have for example `eslint --fix` fix that up for you. The downside is that these tools are much slower than just running Prettier. diff --git a/website/versioned_docs/version-stable/options.md b/website/versioned_docs/version-stable/options.md index ffb36eda0..1c1404fe3 100644 --- a/website/versioned_docs/version-stable/options.md +++ b/website/versioned_docs/version-stable/options.md @@ -4,7 +4,11 @@ title: Options original_id: options --- -Prettier ships with a handful of customizable format options, usable in both the CLI and API. +Prettier ships with a handful of format options. + +**To learn more about Prettier’s stance on options – see the [Option Philosophy](option-philosophy.md).** + +If you change any options, it’s recommended to do it via a [configuration file](configuration.md). This way the Prettier CLI, [editor integrations](editors.md) and other tooling knows what options you use. ## Print Width @@ -12,17 +16,19 @@ 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. +> 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. +> Prettier’s printWidth option does not work the same way. It is not the hard upper allowed line length limit. It is a way to say to Prettier roughly how long you’d like lines to be. Prettier will make both shorter and longer lines, but generally strive to meet the specified printWidth. > -> See the [print width rationale](rationale.md#print-width) for more information. +> Remember, computers are dumb. You need to explicitly tell them what to do, while humans can make their own (implicit) judgements, for example on when to break a line. +> +> In other words, don’t try to use printWidth as if it was ESLint’s [max-len](https://eslint.org/docs/rules/max-len) – they’re not the same. max-len just says what the maximum allowed line length is, but not what the generally preferred length is – which is what printWidth specifies. | Default | CLI Override | API Override | | ------- | --------------------- | ------------------- | | `80` | `--print-width ` | `printWidth: ` | -(If you don't want line wrapping when formatting Markdown, you can set the [Prose Wrap](#prose-wrap) option to disable it.) +(If you don’t want line wrapping when formatting Markdown, you can set the [Prose Wrap](#prose-wrap) option to disable it.) ## Tab Width @@ -195,9 +201,9 @@ These options cannot be used with `cursorOffset`. Specify which parser to use. -Prettier automatically infers the parser from the input file path, so you shouldn't have to change this setting. +Prettier automatically infers the parser from the input file path, so you shouldn’t have to change this setting. -Both the `babel` 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 `babel`. Almost the same applies to `typescript` and `babel-ts`. `babel-ts` might support JavaScript features (proposals) not yet supported by TypeScript, but it's less permissive when it comes to invalid code and less battle-tested than the `typescript` parser. +Both the `babel` 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 `babel`. Almost the same applies to `typescript` and `babel-ts`. `babel-ts` might support JavaScript features (proposals) not yet supported by TypeScript, but it’s less permissive when it comes to invalid code and less battle-tested than the `typescript` parser. Valid options: @@ -241,11 +247,13 @@ For example, the following will use the CSS parser: cat foo | prettier --stdin-filepath foo.css ``` +This option is only useful in the CLI and API. It doesn’t make sense to use it in a configuration file. + | Default | CLI Override | API Override | | ------- | --------------------------- | ---------------------- | | None | `--stdin-filepath ` | `filepath: ""` | -## Require pragma +## Require Pragma _First available in v1.7.0_ @@ -348,7 +356,7 @@ If you want to make sure that your entire git repository only contains Linux-sty 1. Ensure Prettier’s `endOfLine` option is set to `lf` (this is a default value since v2.0.0) 1. Configure [a pre-commit hook](precommit.md) that will run Prettier 1. Configure Prettier to run in your CI pipeline using [`--check` flag](cli.md#--check). If you use Travis CI, set [the `autocrlf` option](https://docs.travis-ci.com/user/customizing-the-build#git-end-of-line-conversion-control) to `input` in `.travis.yml`. -1. Add `* text=auto eol=lf` to the repo's `.gitattributes` file. +1. Add `* text=auto eol=lf` to the repo’s `.gitattributes` file. You may need to ask Windows users to re-clone your repo after this change to ensure git has not converted `LF` to `CRLF` on checkout. All modern text editors in all operating systems are able to correctly display line endings when `\n` (`LF`) is used. @@ -360,7 +368,7 @@ Valid options: - `"crlf"` - Carriage Return + Line Feed characters (`\r\n`), common on Windows - `"cr"` - Carriage Return character only (`\r`), used very rarely - `"auto"` - Maintain existing line endings - (mixed values within one file are normalised by looking at what's used after the first line) + (mixed values within one file are normalised by looking at what’s used after the first line) | Default | CLI Override | API Override | | ------- | ----------------------------------------------------------- | ---------------------------------------------------------- | diff --git a/website/versioned_docs/version-stable/plugins.md b/website/versioned_docs/version-stable/plugins.md index d23f3d2eb..751878f1e 100644 --- a/website/versioned_docs/version-stable/plugins.md +++ b/website/versioned_docs/version-stable/plugins.md @@ -4,13 +4,13 @@ title: Plugins original_id: plugins --- -Plugins are ways of adding new languages to Prettier. The core `prettier` package contains JavaScript and other web-focused languages built in. For additional languages you’ll need to install a plugin. +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-` or `@/prettier-plugin-` to be registered. -> `` should be replaced by a name, read more about [npm scope](https://docs.npmjs.com/misc/scope.html). +> `` should be replaced by a name, read more about [NPM scope](https://docs.npmjs.com/misc/scope.html). When plugins cannot be found automatically, you can load them with: @@ -53,10 +53,13 @@ Providing at least one path to `--plugin-search-dir`/`pluginSearchDirs` turns of - [`prettier-plugin-package`](https://github.com/shellscape/prettier-plugin-package) by [**@shellscape**](https://github.com/shellscape) - [`prettier-plugin-packagejson`](https://github.com/matzkoh/prettier-plugin-packagejson) by [**@matzkoh**](https://github.com/matzkoh) - [`prettier-plugin-pg`](https://github.com/benjie/prettier-plugin-pg) by [**@benjie**](https://github.com/benjie) +- [`prettier-plugin-properties`](https://github.com/eemeli/prettier-plugin-properties) by [**@eemeli**](https://github.com/eemeli) - [`prettier-plugin-solidity`](https://github.com/prettier-solidity/prettier-plugin-solidity) by [**@mattiaerre**](https://github.com/mattiaerre) - [`prettier-plugin-svelte`](https://github.com/UnwrittenFun/prettier-plugin-svelte) by [**@UnwrittenFun**](https://github.com/UnwrittenFun) - [`prettier-plugin-toml`](https://github.com/bd82/toml-tools/tree/master/packages/prettier-plugin-toml) by [**@bd82**](https://github.com/bd82) - [`prettier-plugin-organize-imports`](https://github.com/simonhaenisch/prettier-plugin-organize-imports) by [**@simonhaenisch**](https://github.com/simonhaenisch) +- [`prettier-plugin-pkg`](https://github.com/rx-ts/prettier/tree/master/packages/pkg) by [**@JounQin**](https://github.com/JounQin) +- [`prettier-plugin-sh`](https://github.com/rx-ts/prettier/tree/master/packages/sh) by [**@JounQin**](https://github.com/JounQin) ## Developing Plugins @@ -164,7 +167,7 @@ function print( ): Doc; ``` -Check out [prettier-python's printer](https://github.com/prettier/prettier-python/blob/034ba8a9551f3fa22cead41b323be0b28d06d13b/src/printer.js#L174) as an example. +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: @@ -182,7 +185,7 @@ function embed( ): Doc | null; ``` -If you don't want to switch to a different parser, simply return `null` or `undefined`. +If an `embed` function is included, it will be called _first_ on every node. If the `embed` function returns a falsy value, the current plugin’s `print` function is called. Otherwise, the `Doc` returned by the `embed` function is used. The `embed` function is passed `textToDoc` which can be called with a suitable `options` argument to obtain the `Doc` produced by a different plugin (which can then be directly returned or used inside a larger `Doc` construction). For example, to print embedded JavaScript, a plugin might return `textToDoc(javaScriptText, { parser: "babel" })` from the `embed` function. 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: @@ -215,7 +218,7 @@ options: { ### `defaultOptions` -If your plugin requires different default values for some of Prettier's core options, you can specify them in `defaultOptions`: +If your plugin requires different default values for some of Prettier’s core options, you can specify them in `defaultOptions`: ``` defaultOptions: { diff --git a/website/versioned_docs/version-stable/precommit.md b/website/versioned_docs/version-stable/precommit.md index d782a8673..8cdd0c31e 100644 --- a/website/versioned_docs/version-stable/precommit.md +++ b/website/versioned_docs/version-stable/precommit.md @@ -4,7 +4,7 @@ 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. +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) @@ -18,7 +18,7 @@ npx mrm lint-staged This will install [husky](https://github.com/typicode/husky) and [lint-staged](https://github.com/okonet/lint-staged), then add a configuration to the project’s `package.json` that will automatically format supported files in a pre-commit hook. -See https://github.com/okonet/lint-staged#configuration for more details about how you can configure lint-staged. +Read more at the [lint-staged](https://github.com/okonet/lint-staged#configuration) repo. ## Option 2. [pretty-quick](https://github.com/azz/pretty-quick) @@ -26,11 +26,22 @@ See https://github.com/okonet/lint-staged#configuration for more details about h Install it along with [husky](https://github.com/typicode/husky): + + + ```bash -yarn add pretty-quick husky --dev +npm install --save-dev pretty-quick husky ``` -and add this config to your `package.json`: + + +```bash +yarn add --dev pretty-quick husky +``` + + + +Add this to your `package.json`: ```json { @@ -42,7 +53,7 @@ and add this config to your `package.json`: } ``` -Find more info from [here](https://github.com/azz/pretty-quick). +Read more at the [pretty-quick](https://github.com/azz/pretty-quick) repo. ## Option 3. [pre-commit](https://github.com/pre-commit/pre-commit) @@ -57,7 +68,7 @@ Copy the following config into your `.pre-commit-config.yaml` file: - id: prettier ``` -Find more info from [here](https://pre-commit.com). +Read more at the [pre-commit](https://pre-commit.com) website. ## Option 4. [precise-commits](https://github.com/JamesHenry/precise-commits) @@ -65,10 +76,21 @@ Find more info from [here](https://pre-commit.com). Install it along with [husky](https://github.com/typicode/husky): + + + ```bash -yarn add precise-commits husky --dev +npm install --save-dev precise-commits husky ``` + + +```bash +yarn add --dev precise-commits husky +``` + + + and add this config to your `package.json`: ```json @@ -81,9 +103,7 @@ and add this config to your `package.json`: } ``` -**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). +Read more at the [precise-commits](https://github.com/JamesHenry/precise-commits#2-precommit-hook) repo. ## Option 5. [git-format-staged](https://github.com/hallettj/git-format-staged) @@ -93,22 +113,33 @@ Git-format-staged is used to run any formatter that can accept file content via 1. Changes in commits are always formatted. 2. Unstaged changes are never, under any circumstances staged during the formatting process. -3. If there are conflicts between formatted, staged changes and unstaged changes then your working tree files are left untouched - your work won't be overwritten, and there are no stashes to clean up. +3. If there are conflicts between formatted, staged changes and unstaged changes then your working tree files are left untouched - your work won’t be overwritten, and there are no stashes to clean up. 4. Unstaged changes are not formatted. Git-format-staged requires Python v3 or v2.7. Python is usually pre-installed on Linux and macOS, but not on Windows. Use git-format-staged with [husky](https://github.com/typicode/husky): + + + ```bash -yarn add --dev husky prettier git-format-staged +npm install --save-dev git-format-staged husky ``` + + +```bash +yarn add --dev git-format-staged husky +``` + + + and add this config to your `package.json`: ```json { "husky": { "hooks": { - "pre-commit": "git-format-staged -f 'prettier --stdin --stdin-filepath \"{}\"' '*.js' '*.jsx' '*.ts' '*.tsx' '*.css' '*.json' '*.gql'" + "pre-commit": "git-format-staged -f 'prettier --stdin --stdin-filepath \"{}\"' ." } } } @@ -118,11 +149,11 @@ Add or remove file extensions to suit your project. Note that regardless of whic To read about how git-format-staged works see [Automatic Code Formatting for Partially-Staged Files](https://www.olioapps.com/blog/automatic-code-formatting/). -## Option 6. bash script +## Option 6. Shell script Alternately you can save this script as `.git/hooks/pre-commit` and give it execute permission: -```bash +```sh #!/bin/sh FILES=$(git diff --cached --name-only --diff-filter=ACMR "*.js" "*.jsx" | sed 's| |\\ |g') [ -z "$FILES" ] && exit 0 @@ -136,11 +167,11 @@ echo "$FILES" | 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). +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](https://github.com/prettier/prettier/issues/2978#issuecomment-334408427). Add something like the following to `.git/hooks/post-commit`: -```bash +```sh #!/bin/sh git update-index -g ``` diff --git a/website/versioned_docs/version-stable/rationale.md b/website/versioned_docs/version-stable/rationale.md index e9a84318b..f858077a3 100644 --- a/website/versioned_docs/version-stable/rationale.md +++ b/website/versioned_docs/version-stable/rationale.md @@ -10,16 +10,16 @@ Prettier is an opinionated code formatter. This document explains some of its ch ### 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! +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). +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 or the string not containing any quotes, Prettier defaults to double quotes (but that can be changed via the [singleQuote](options.html#quotes) option). -JSX has its own option for quotes: [`--jsx-single-quote`](options.html#jsx-quotes). +JSX has its own option for quotes: [jsxSingleQuote](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. +Prettier maintains the way your string is escaped. For example, `"🙂"` won’t be formatted into `"\uD83D\uDE42"` and vice versa. ### Empty lines @@ -30,9 +30,9 @@ It turns out that empty lines are very hard to automatically generate. The appro ### Multi-line objects -By default, Prettier’s 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. +By default, Prettier’s 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: +**Tip:** If you have a multiline object that you’d like to join up into a single line: ```js const user = { @@ -56,7 +56,7 @@ const user = { name: "John Doe", const user = { name: "John Doe", age: 30 }; ``` -And if you'd like to go multiline again, add in a newline after `{`: +And if you’d like to go multiline again, add in a newline after `{`: ```js @@ -80,7 +80,7 @@ const user = { ### 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. +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({ @@ -100,7 +100,7 @@ class HeroButtonComponent { } ``` -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. +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. ```js @@ -140,7 +140,7 @@ export @decorator class Foo {} ### Semicolons -This is about using the [`--no-semi`](options.md#semicolons) option. +This is about using the [noSemi](options.md#semicolons) option. Consider this piece of code: @@ -186,7 +186,7 @@ This practice is also common in [standard] which uses a semicolon-free style. ### 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.” +The [printWidth](options.md#print-width) option is more of a guideline to Prettier than a hard rule. It is not the upper allowed line length limit. It is a way to say to Prettier roughly how long you’d like lines to be. Prettier will make both shorter and longer lines, but generally strive to meet the specified print width. 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 doesn’t 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 :) @@ -203,7 +203,7 @@ import { } 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: +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"; @@ -263,7 +263,7 @@ Secondly, [the alternate formatting makes it easier to edit the JSX](https://git ### Comments -When it comes to the _contents_ of comments, Prettier can’t do much really. Comments can contain everything from prose to commented out code and ASCII diagrams. Since they can contain anything, Prettier can’t 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. +When it comes to the _content_ of comments, Prettier can’t do much really. Comments can contain everything from prose to commented out code and ASCII diagrams. Since they can contain anything, Prettier can’t 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 there’s the question of _where_ to put the comments. Turns out this is a really difficult problem. Prettier tries its best to keep your comments roughly where they were, but it’s no easy task because comments can be placed almost anywhere. @@ -294,7 +294,7 @@ 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: +Which means that the `eslint-disable-next-line` comment is no longer effective. In this case you need to move the comment: ```js const result = @@ -302,9 +302,15 @@ const result = safeToEval && settings.allowNativeEval ? eval(input) : fallback(input); ``` +If possible, prefer comments that operate on line ranges (e.g. `eslint-disable` and `eslint-enable`) or on the statement level (e.g. `/* istanbul ignore next */`), they are even safer. It’s possible to disallow using `eslint-disable-line` and `eslint-disable-next-line` comments using [`eslint-plugin-eslint-comments`](https://github.com/mysticatea/eslint-plugin-eslint-comments). + +## Disclaimer about non-standard syntax + +Prettier is often able to recognize and format non-standard syntax such as ECMAScript early-stage proposals and Markdown syntax extensions not defined by any specification. The support for such syntax is considered best-effort and experimental. Incompatibilities may be introduced in any release and should not be viewed as breaking changes. + ## 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! +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: diff --git a/website/versioned_docs/version-stable/related-projects.md b/website/versioned_docs/version-stable/related-projects.md index f330e954c..5f32ad465 100644 --- a/website/versioned_docs/version-stable/related-projects.md +++ b/website/versioned_docs/version-stable/related-projects.md @@ -6,37 +6,31 @@ 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` +- [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) turns off all ESLint rules that are unnecessary or might conflict with Prettier +- [eslint-plugin-prettier](https://github.com/prettier/eslint-plugin-prettier) runs Prettier as an ESLint rule and reports differences as individual ESLint issues +- [prettier-eslint](https://github.com/prettier/prettier-eslint) passes `prettier` output to `eslint --fix` +- [prettier-standard](https://github.com/sheerun/prettier-standard) uses `prettierx` and `prettier-eslint` to format code with `standard` rules ## 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` +- [stylelint-config-prettier](https://github.com/prettier/stylelint-config-prettier) turns off all rules that are unnecessary or might conflict with Prettier. +- [stylelint-prettier](https://github.com/prettier/stylelint-prettier) runs Prettier as a stylelint rule and reports differences as individual stylelint issues +- [prettier-stylelint](https://github.com/hugomrdias/prettier-stylelint) passes `prettier` output to `stylelint --fix` + +## TSLint Integrations + +- [tslint-config-prettier](https://github.com/alexjoverm/tslint-config-prettier) use TSLint with Prettier without any conflict +- [tslint-plugin-prettier](https://github.com/ikatyang/tslint-plugin-prettier) runs Prettier as a TSLint rule and reports differences as individual TSLint issues +- [prettier-tslint](https://github.com/azz/prettier-tslint) passes `prettier` output to `tslint --fix` ## Forks -- [`prettier-miscellaneous`](https://github.com/arijs/prettier-miscellaneous) `prettier` with a few minor extra options +- [prettierx](https://github.com/brodybits/prettierx) less opinionated fork of Prettier ## 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 -- [`jest-runner-prettier`](https://github.com/keplersj/jest-runner-prettier) run Prettier as a Jest runner +- [prettier_d](https://github.com/josephfrazier/prettier_d.js) runs Prettier as a server to avoid Node.js startup delay +- [pretty-quick](https://github.com/azz/pretty-quick) formats changed files with Prettier +- [rollup-plugin-prettier](https://github.com/mjeanroy/rollup-plugin-prettier) allows you to use Prettier with Rollup +- [jest-runner-prettier](https://github.com/keplersj/jest-runner-prettier) is Prettier as a Jest runner +- [prettier-chrome](https://github.com/u3u/prettier-chrome) is an extension that runs Prettier in the browser diff --git a/website/versioned_docs/version-stable/technical-details.md b/website/versioned_docs/version-stable/technical-details.md index d8a030422..64aff50e8 100644 --- a/website/versioned_docs/version-stable/technical-details.md +++ b/website/versioned_docs/version-stable/technical-details.md @@ -4,10 +4,10 @@ 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](https://homepages.inf.ed.ac.uk/wadler/papers/prettier/prettier.pdf)". There still may be leftover code from recast that needs to be cleaned up. +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](https://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. +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). diff --git a/website/versioned_docs/version-stable/vim.md b/website/versioned_docs/version-stable/vim.md index a95b21737..dfcae95aa 100644 --- a/website/versioned_docs/version-stable/vim.md +++ b/website/versioned_docs/version-stable/vim.md @@ -39,7 +39,7 @@ 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`: +It’s recommended to use a [config file](configuration.md), but you can also add options in your `.vimrc`: ```vim autocmd FileType javascript setlocal formatprg=prettier\ --single-quote\ --trailing-comma\ es5 @@ -47,7 +47,7 @@ autocmd FileType javascript setlocal formatprg=prettier\ --single-quote\ --trail let g:neoformat_try_formatprg = 1 ``` -Each space in prettier options should be escaped with `\`. +Each space in Prettier options should be escaped with `\`. ## [ALE](https://github.com/dense-analysis/ale) @@ -72,7 +72,7 @@ let g:ale_fixers = { \} ``` -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/dense-analysis/ale/blob/ed8104b6ab10f63c78e49b60d2468ae2656250e9/README.md#faq-disable-linters)): +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/dense-analysis/ale/blob/ed8104b6ab10f63c78e49b60d2468ae2656250e9/README.md#faq-disable-linters)): ```vim let g:ale_linters_explicit = 1 @@ -86,10 +86,10 @@ 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`: +It’s recommended to use a [config file](configuration.md), but you can also add options in your `.vimrc`: ```vim -let g:ale_javascript_prettier_options = '--single-quote --trailing-comma es5' +let g:ale_javascript_prettier_options = '--single-quote --trailing-comma all' ``` ## [coc-prettier](https://github.com/neoclide/coc-prettier) @@ -98,7 +98,7 @@ Prettier extension for [coc.nvim](https://github.com/neoclide/coc.nvim) which re Install coc.nvim with your favorite plugin manager, such as [vim-plug](https://github.com/junegunn/vim-plug): ```vim -Plug 'neoclide/coc.nvim', {'do': { -> coc#util#install()}} +Plug 'neoclide/coc.nvim', {'branch': 'release'} ``` And install coc-prettier by command: @@ -128,9 +128,9 @@ Update your `coc-settings.json` for languages that you want format on save. 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: ```vim -nnoremap gp :silent %!prettier --stdin-filepath % --trailing-comma all --single-quote +nnoremap gp :silent %!prettier --stdin-filepath % ``` -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. +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. +Another disadvantage of this approach is that the cursor position won’t be preserved. diff --git a/website/versioned_docs/version-stable/watching-files.md b/website/versioned_docs/version-stable/watching-files.md index 0d0eb3eb3..0ef379cc9 100644 --- a/website/versioned_docs/version-stable/watching-files.md +++ b/website/versioned_docs/version-stable/watching-files.md @@ -4,13 +4,13 @@ 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: +You can have Prettier watch for changes from the command line by using [onchange](https://www.npmjs.com/package/onchange). For example: ```bash npx onchange '**/*.js' -- npx prettier --write {{changed}} ``` -or add the following to your `package.json` +Or add the following to your `package.json`: ```json { diff --git a/website/versioned_docs/version-stable/webstorm.md b/website/versioned_docs/version-stable/webstorm.md index c05f5e024..afaefa9d8 100644 --- a/website/versioned_docs/version-stable/webstorm.md +++ b/website/versioned_docs/version-stable/webstorm.md @@ -6,13 +6,13 @@ original_id: webstorm ## Using Prettier in WebStorm -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. +Use the `Reformat with Prettier` action (`Opt-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. To run Prettier on save in WebStorm 2020.1 or above, open _Preferences | Languages & Frameworks | JavaScript | Prettier_ and enable the option `Run on save for files`. By default, only JavaScript and TypeScript files will be formatted automatically. You can further configure what files will be updated using the [glob pattern](https://github.com/isaacs/node-glob#glob-primer). -Don't forget to install Prettier first. +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). @@ -31,15 +31,13 @@ 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$` +- **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] $FilePath$` - **Output paths to refresh**: `$FilePathRelativeToProjectRoot$` - **Working directory**: `$ProjectFileDir$` - **Environment variables**: add `COMPILE_PARTIAL=true` if you want to run Prettier on partials (like `_component.scss`) - **Auto-save edited files to trigger the watcher**: Uncheck to reformat on Save only. -![Example](/docs/assets/webstorm/file-watcher-prettier.png) - ## 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 current 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. @@ -51,7 +49,7 @@ Make sure that the ESLint integration is enabled in _Preferences | Languages & F Go to _Preferences | Tools | External Tools_ and click **+** to add a new tool. Let’s 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$` +- **Parameters**: `--write [other options] $FilePath$` - **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. diff --git a/website/versioned_docs/version-stable/why-prettier.md b/website/versioned_docs/version-stable/why-prettier.md index 994853b8b..14e120574 100644 --- a/website/versioned_docs/version-stable/why-prettier.md +++ b/website/versioned_docs/version-stable/why-prettier.md @@ -8,22 +8,22 @@ original_id: why-prettier 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? +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.” +- “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.” +- “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. +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.” +- “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.” @@ -33,16 +33,16 @@ What usually happens once people are using Prettier is that they realize that th - “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 :(“ +- “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.” +- “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.” +- “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 @@ -54,7 +54,7 @@ Since coming up with a coding style and enforcing it is a big undertaking, it of ## 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. +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.” diff --git a/website/versioned_sidebars/version-stable-sidebars.json b/website/versioned_sidebars/version-stable-sidebars.json index 651982d84..719e0d077 100644 --- a/website/versioned_sidebars/version-stable-sidebars.json +++ b/website/versioned_sidebars/version-stable-sidebars.json @@ -9,14 +9,13 @@ ], "Usage": [ "version-stable-install", + "version-stable-ignore", + "version-stable-integrating-with-linters", + "version-stable-precommit", + "version-stable-plugins", "version-stable-cli", "version-stable-api", - "version-stable-browser", - "version-stable-plugins", - "version-stable-precommit", - "version-stable-watching-files", - "version-stable-integrating-with-linters", - "version-stable-ignore" + "version-stable-browser" ], "Configuring Prettier": [ "version-stable-options", @@ -25,7 +24,8 @@ "Editors": [ "version-stable-editors", "version-stable-webstorm", - "version-stable-vim" + "version-stable-vim", + "version-stable-watching-files" ], "Misc": [ "version-stable-technical-details",