### API --- id: api title: API --- If you want to run Prettier programmatically, check this page out. ```js import * as prettier from "prettier"; ``` Our public APIs are all asynchronous, if you must use synchronous version for some reason, you can try [`@prettier/sync`](https://github.com/prettier/prettier-synchronized). ## `prettier.format(source, options)` `format` is used to format text using Prettier. `options.parser` must be set according to the language you are formatting (see the [list of available parsers](options.md#parser)). Alternatively, `options.filepath` can be specified for Prettier to infer the parser from the file extension. Other [options](options.md) may be provided to override the defaults. ```js await prettier.format("foo ( );", { semi: false, parser: "babel" }); // -> 'foo()\n' ``` ## `prettier.check(source [, options])` `check` checks to see if the file has been formatted with Prettier given those options and returns a `Promise`. This is similar to the `--check` or `--list-different` parameter in the CLI and is useful for running Prettier in CI scenarios. ## `prettier.formatWithCursor(source [, options])` `formatWithCursor` both formats the code, and translates a cursor position from unformatted code to formatted code. This is useful for editor integrations, to prevent the cursor from moving when code is formatted. The `cursorOffset` option should be provided, to specify where the cursor is. ```js await prettier.formatWithCursor(" 1", { cursorOffset: 2, parser: "babel" }); // -> { formatted: '1;\n', cursorOffset: 1 } ``` ## `prettier.resolveConfig(fileUrlOrPath [, options])` `resolveConfig` can be used to resolve configuration for a given source file, passing its path or url as the first argument. The config search will start at the directory of the file location and continue to search up the directory. Or you can pass directly the path of the config file as `options.config` if you don’t wish to search for it. A promise is returned which will resolve to: - An options object, providing a [config file](configuration.md) was found. - `null`, if no file was found. The promise will be rejected if there was an error parsing the configuration file. If `options.useCache` is `false`, all caching will be bypassed. ```js const text = await fs.readFile(filePath, "utf8"); const options = await prettier.resolveConfig(filePath); const formatted = await prettier.format(text, { ...options, filepath: filePath, }); ``` 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` ## `prettier.resolveConfigFile([fileUrlOrPath])` `resolveConfigFile` can be used to find the path of the Prettier configuration file that will be used when resolving the config (i.e. when calling `resolveConfig`). A promise is returned which will resolve to: - The path of the configuration file. - `null`, if no file was found. The promise will be rejected if there was an error parsing the configuration file. The search starts at `process.cwd()`, or at the directory of `fileUrlOrPath` if provided. ```js const configFile = await prettier.resolveConfigFile(filePath); // you got the path of the configuration file ``` ## `prettier.clearConfigCache()` When Prettier loads configuration files and plugins, the file system structure is cached for performance. This function will clear the cache. Generally this is only needed for editor integrations that know that the file system has changed since the last format took place. ## `prettier.getFileInfo(fileUrlOrPath [, options])` `getFileInfo` can be used by editor extensions to decide if a particular file needs to be formatted. This method returns a promise, which resolves to an object with the following properties: ```ts { ignored: boolean; inferredParser: string | null; } ``` The promise will be rejected if the type of `fileUrlOrPath` is not `string` or `URL`. Setting `options.ignorePath` (`string | URL | (string | URL)[]`) and `options.withNodeModules` (`boolean`) influence the value of `ignored` (`false` by default). If the given `fileUrlOrPath` 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 `true`) to `false`, Prettier will not search for configuration file. This can be useful if this function is only used to check if file is ignored. ## `prettier.getSupportInfo()` Returns a promise which resolves to an object representing the options, parsers, languages and file types Prettier supports. The support information looks like this: ```ts { languages: Array<{ name: string; parsers: string[]; group?: string; tmScope?: string; aceMode?: string; codemirrorMode?: string; codemirrorMimeType?: string; aliases?: string[]; extensions?: string[]; filenames?: string[]; linguistLanguageId?: number; vscodeLanguageIds?: string[]; }>; } ``` ## Custom Parser API (removed) _Removed in v3.0.0 (superseded by the Plugin API)_ Before [plugins](plugins.md) were a thing, Prettier had a similar but more limited feature called custom parsers. It’s been removed in v3.0.0 as its functionality was a subset of what the Plugin API did. If you used it, please check the example below on how to migrate. ❌ Custom parser API (removed): ```js import { format } from "prettier"; format("lodash ( )", { parser(text, { babel }) { const ast = babel(text); ast.program.body[0].expression.callee.name = "_"; return ast; }, }); // -> "_();\n" ``` ✔️ Plugin API: ```js import { format } from "prettier"; import * as prettierPluginBabel from "prettier/plugins/babel"; const myCustomPlugin = { parsers: { "my-custom-parser": { async parse(text) { const ast = await prettierPluginBabel.parsers.babel.parse(text); ast.program.body[0].expression.callee.name = "_"; return ast; }, astFormat: "estree", }, }, }; await format("lodash ( )", { parser: "my-custom-parser", plugins: [myCustomPlugin], }); // -> "_();\n" ``` :::note Overall, doing codemods this way isn’t recommended. Prettier uses the location data of AST nodes for many things like preserving blank lines and attaching comments. When the AST is modified after the parsing, the location data often gets out of sync, which may lead to unpredictable results. Consider using [jscodeshift](https://github.com/facebook/jscodeshift) if you need codemods. ::: As part of the removed Custom parser API, it was previously possible to pass a path to a module exporting a `parse` function via the `--parser` option. Use the `--plugin` CLI option or the `plugins` API option instead to [load plugins](plugins.md#using-plugins). --- ### Browser --- id: browser title: Browser --- import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; Run Prettier in the browser using its **standalone** version. This version doesn’t depend on Node.js. It only formats the code and has no support for config files, ignore files, CLI usage, or automatic loading of plugins. The standalone version comes as: - ES modules: `standalone.mjs`, starting in version 3.0 (In version 2, `esm/standalone.mjs`.) - UMD: `standalone.js`, starting in version 1.13 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)` Required options: - **[`parser`](options.md#parser) (or [`filepath`](options.md#file-path))**: One of these options has to be specified for Prettier to know which parser to use. - **`plugins`**: Unlike the `format` function from the [Node.js-based API](api.md#prettierformatsource-options), this function doesn’t load plugins automatically. The `plugins` option is required because all the parsers included in the Prettier package come as plugins (for reasons of file size). These plugins are files in [https://unpkg.com/browse/prettier@3.5.3/plugins](https://unpkg.com/browse/prettier@3.5.3/plugins). Note that `estree` plugin should be loaded when printing JavaScript, TypeScript, Flow, or JSON. You need to load the ones that you’re going to use and pass them to `prettier.format` using the `plugins` option. See below for examples. ## Usage ### Global ```html ``` 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 ```html ``` ### AMD ```js define([ "https://unpkg.com/prettier@3.5.3/standalone.js", "https://unpkg.com/prettier@3.5.3/plugins/graphql.js", ], async (prettier, ...plugins) => { const formatted = await prettier.format("type Query { hello: String }", { parser: "graphql", plugins, }); }); ``` ### CommonJS ```js const prettier = require("prettier/standalone"); const plugins = [require("prettier/plugins/graphql")]; (async () => { const formatted = await prettier.format("type Query { hello: String }", { parser: "graphql", plugins, }); })(); ``` This syntax doesn’t necessarily work in the browser, but it can be used when bundling the code with browserify, Rollup, webpack, or another bundler. ### Worker ```js import * as prettier from "https://unpkg.com/prettier@3.5.3/standalone.mjs"; import * as prettierPluginGraphql from "https://unpkg.com/prettier@3.5.31/plugins/graphql.mjs"; const formatted = await prettier.format("type Query { hello: String }", { parser: "graphql", plugins: [prettierPluginGraphql], }); ``` ```js importScripts( "https://unpkg.com/prettier@3.5.3/standalone.js", "https://unpkg.com/prettier@3.5.3/plugins/graphql.js", ); (async () => { const formatted = await prettier.format("type Query { hello: String }", { parser: "graphql", plugins: prettierPlugins, }); })(); ``` ## Parser plugins for embedded code If you want to format [embedded code](options.md#embedded-language-formatting), you need to load related plugins too. For example: ```html ``` The HTML code embedded in JavaScript stays unformatted because the `html` parser hasn’t been loaded. Correct usage: ```html ``` --- ### Run Prettier on CI --- id: ci title: Run Prettier on CI --- ## GitHub Actions To apply autofix for Prettier from GitHub Actions, do the following: 1. Install the [`autofix.ci`](https://github.com/apps/autofix-ci) GitHub App. 1. Make sure you have a **pinned** version of Prettier installed in your repository. 1. Create `.github/workflows/prettier.yml` with following content: ```yaml title=".github/workflows/prettier.yml" name: autofix.ci on: pull_request: push: permissions: {} jobs: prettier: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 - run: | yarn yarn prettier . --write - uses: autofix-ci/action@v1 with: commit-message: "Apply Prettier format" ``` For more information see [autofix.ci](https://autofix.ci/) website. --- ### CLI --- id: cli title: CLI --- Use the `prettier` command to run Prettier from the command line. ```bash prettier [options] [file/dir/glob ...] ``` :::note To run your locally installed version of Prettier, prefix the command with `npx`, `yarn exec`, `pnpm exec`, or `bun exec`, i.e. `npx prettier --help`, `yarn exec prettier --help`, `pnpm exec prettier --help`, or `bun exec prettier --help`. ::: To format a file in-place, use `--write`. (Note: This overwrites your files!) In practice, this may look something like: ```bash 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 docs package.json "{app,__{tests,mocks}__}/**/*.js" --write --single-quote --trailing-comma all ``` :::warning 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. ::: :::note 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. ::: ## File patterns 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. - Otherwise, the entry is resolved as a glob pattern using the [glob syntax from the `fast-glob` module](https://github.com/mrmlnc/fast-glob#pattern-syntax). Prettier CLI will ignore files located in `node_modules` directory. To opt out from this behavior, use `--with-node-modules` flag. Prettier CLI will not follow symbolic links when expanding arguments. 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` When you want to check if your files are formatted, you can run Prettier with the `--check` flag (or `-c`). This will output a human-friendly message and a list of unformatted files, if any. ```bash prettier . --check ``` Console output if all files are formatted: ```console Checking formatting... All matched files use Prettier code style! ``` Console output if some of the files require re-formatting: ```console Checking formatting... [warn] src/fileA.js [warn] src/fileB.js [warn] Code style issues found in 2 files. Run Prettier with --write to fix. ``` The command will return exit code `1` in the second case, which is helpful inside the CI pipelines. Human-friendly status messages help project contributors react on possible problems. To minimise the number of times `prettier --check` finds unformatted files, you may be interested in configuring a [pre-commit hook](precommit.md) in your repo. Applying this practice will minimise the number of times the CI fails because of code formatting problems. If you need to pipe the list of unformatted files to another command, you can use [`--list-different`](cli.md#--list-different) flag instead of `--check`. ### Exit codes | Code | Information | | ---- | ----------------------------------- | | `0` | Everything formatted properly | | `1` | Something wasn’t formatted properly | | `2` | Something’s wrong with Prettier | ## `--debug-check` If you're worried that Prettier will change the correctness of your code, add `--debug-check` to the command. This will cause Prettier to print an error message if it detects that code correctness might have changed. Note that `--write` cannot be used with `--debug-check`. ## `--find-config-path` and `--config` If you are repeatedly formatting individual files with `prettier`, you will incur a small performance cost when Prettier attempts to look up a [configuration file](configuration.md). In order to skip this, you may ask Prettier to find the config file once, and re-use it later on. ```console $ prettier --find-config-path path/to/file.js path/to/.prettierrc ``` This will provide you with a path to the configuration file, which you can pass to `--config`: ```bash prettier path/to/file.js --write --config path/to/.prettierrc ``` You can also use `--config` if your configuration file lives somewhere where Prettier cannot find it, such as a `config/` directory. If you don’t have a configuration file, or want to ignore it if it does exist, you can pass `--no-config` instead. ## `--ignore-path` Path to a file containing patterns that describe files to ignore. By default, Prettier looks for `./.gitignore` and `./.prettierignore`.\ Multiple values are accepted. ## `--list-different` Another useful flag is `--list-different` (or `-l`) which prints the filenames of files that are different from Prettier formatting. If there are differences the script errors out, which is useful in a CI scenario. ```bash prettier . --single-quote --list-different ``` You can also use [`--check`](cli.md#--check) flag, which works the same way as `--list-different`, but also prints a human-friendly summary message to stdout. ## `--no-config` Do not look for a configuration file. The default settings will be used. ## `--config-precedence` Defines how config file should be evaluated in combination of CLI options. **cli-override (default)** CLI options take precedence over config file **file-override** Config file take precedence over CLI options **prefer-file** If a config file is found will evaluate it and ignore other CLI options. If no config file is found, CLI options will evaluate as normal. This option adds support to editor integrations where users define their default configuration but want to respect project specific configuration. ## `--no-editorconfig` Don’t take `.editorconfig` into account when parsing configuration. See the [`prettier.resolveConfig` docs](api.md) for details. ## `--with-node-modules` Prettier CLI will ignore files located in `node_modules` directory. To opt out from this behavior, use `--with-node-modules` flag. ## `--write` This rewrites all processed files in place. This is comparable to the `eslint --fix` workflow. You can also use `-w` alias. ## `--log-level` Change the level of logging for the CLI. Valid options are: - `error` - `warn` - `log` (default) - `debug` - `silent` ## `--stdin-filepath` A path to the file that the Prettier CLI will treat like stdin. For example: _abc.css_ ```css .name { display: none; } ``` _shell_ ```console $ cat abc.css | prettier --stdin-filepath abc.css .name { display: none; } ``` ## `--ignore-unknown` With `--ignore-unknown` (or `-u`), prettier will ignore unknown files matched by patterns. ```bash prettier "**/*" --write --ignore-unknown ``` ## `--no-error-on-unmatched-pattern` Prevent errors when pattern is unmatched. ## `--cache` If this option is enabled, the following values are used as cache keys and the file is formatted only if one of them is changed. - Prettier version - Options - Node.js version - (if `--cache-strategy` is `metadata`) file metadata, such as timestamps - (if `--cache-strategy` is `content`) content of the file ```bash prettier . --write --cache ``` Running Prettier without `--cache` will delete the cache. Also, since the cache file is stored in `./node_modules/.cache/prettier/.prettier-cache`, so you can use `rm ./node_modules/.cache/prettier/.prettier-cache` to remove it manually. :::warning Plugins version and implementation are not used as cache keys. We recommend that you delete the cache when updating plugins. ::: ## `--cache-location` Path to the cache file location used by `--cache` flag. If you don't explicit `--cache-location`, Prettier saves cache file at `./node_modules/.cache/prettier/.prettier-cache`. If a file path is passed, that file is used as the cache file. ```bash prettier . --write --cache --cache-location=path/to/cache-file ``` ## `--cache-strategy` Strategy for the cache to use for detecting changed files. Can be either `metadata` or `content`. In general, `metadata` is faster. However, `content` is useful for updating the timestamp without changing the file content. This can happen, for example, during git operations such as `git clone`, because it does not track file modification times. If no strategy is specified, `content` will be used. ```bash prettier . --write --cache --cache-strategy metadata ``` --- ### Prettier vs. Linters --- id: comparison title: Prettier vs. Linters --- ## How does it compare to ESLint/TSLint/stylelint, etc.? 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 :) **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!** --- ### Configuration File --- id: configuration title: Configuration File --- You can configure Prettier via (in order of precedence): - A `"prettier"` key in your `package.json`, or [`package.yaml`](https://github.com/pnpm/pnpm/pull/1799) file. - A `.prettierrc` file written in JSON or YAML. - A `.prettierrc.json`, `.prettierrc.yml`, `.prettierrc.yaml`, or `.prettierrc.json5` file. - A `.prettierrc.js`, `prettier.config.js`, `.prettierrc.ts`, or `prettier.config.ts` file that exports an object using `export default` or `module.exports` (depends on the [`type`](https://nodejs.org/api/packages.html#type) value in your `package.json`). - A `.prettierrc.mjs`, `prettier.config.mjs`, `.prettierrc.mts`, or `prettier.config.mts` file that exports an object using `export default`. - A `.prettierrc.cjs`, `prettier.config.cjs`, `.prettierrc.cts`, or `prettier.config.cts` file that exports an object using `module.exports`. - A `.prettierrc.toml` file. :::info TypeScript configuration files support requires [additional setup](#typescript-configuration-files) ::: 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. 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). ### TypeScript Configuration Files TypeScript support for Node.js is currently experimental, Node.js>=22.6.0 is required and `--experimental-strip-types` is required to run Node.js. ```sh node --experimental-strip-types node_modules/prettier/bin/prettier.cjs . --write ``` or ```sh NODE_OPTIONS="--experimental-strip-types" prettier . --write ``` ## Basic Configuration JSON: ```json { "trailingComma": "es5", "tabWidth": 4, "semi": false, "singleQuote": true } ``` JS (ES Modules): ```js // prettier.config.js, .prettierrc.js, prettier.config.mjs, or .prettierrc.mjs /** * @see https://prettier.io/docs/configuration * @type {import("prettier").Config} */ const config = { trailingComma: "es5", tabWidth: 4, semi: false, singleQuote: true, }; export default config; ``` JS (CommonJS): ```js // prettier.config.js, .prettierrc.js, prettier.config.cjs, or .prettierrc.cjs /** * @see https://prettier.io/docs/configuration * @type {import("prettier").Config} */ const config = { trailingComma: "es5", tabWidth: 4, semi: false, singleQuote: true, }; module.exports = config; ``` TypeScript (ES Modules): ```ts // prettier.config.ts, .prettierrc.ts, prettier.config.mts, or .prettierrc.mts import { type Config } from "prettier"; const config: Config = { trailingComma: "none", }; export default config; ``` TypeScript (CommonJS): ```ts // prettier.config.ts, .prettierrc.ts, prettier.config.cts, or .prettierrc.cts import { type Config } from "prettier"; const config: Config = { trailingComma: "none", }; module.exports = config; ``` YAML: ```yaml # .prettierrc or .prettierrc.yaml trailingComma: "es5" tabWidth: 4 semi: false singleQuote: true ``` TOML: ```toml # .prettierrc.toml trailingComma = "es5" tabWidth = 4 semi = false singleQuote = true ``` ## Configuration Overrides Overrides let you have different configuration for certain file extensions, folders and specific files. Prettier borrows ESLint’s [override format](https://eslint.org/docs/latest/user-guide/configuring/configuration-files#how-do-overrides-work). JSON: ```json { "semi": false, "overrides": [ { "files": "*.test.js", "options": { "semi": true } }, { "files": ["*.html", "legacy/**/*.js"], "options": { "tabWidth": 4 } } ] } ``` YAML: ```yaml semi: false overrides: - files: "*.test.js" options: semi: true - files: - "*.html" - "legacy/**/*.js" options: tabWidth: 4 ``` `files` is required for each override, and may be a string or array of strings. `excludeFiles` may be optionally provided to exclude files for a given rule, and may also be a string or array of strings. ## Setting the [parser](options.md#parser) option By default, Prettier automatically infers which parser to use based on the input file extension. Combined with `overrides` you can teach Prettier how to parse files it does not recognize. For example, to get Prettier to format its own `.prettierrc` file, you can do: ```json { "overrides": [ { "files": ".prettierrc", "options": { "parser": "json" } } ] } ``` You can also switch to the `flow` parser instead of the default `babel` for .js files: ```json { "overrides": [ { "files": "*.js", "options": { "parser": "flow" } } ] } ``` **Note:** _Never_ put the `parser` option at the top level of your configuration. _Only_ use it inside `overrides`. Otherwise you effectively disable Prettier’s automatic file extension based parser inference. This forces Prettier to use the parser you specified for _all_ types of files – even when it doesn’t make sense, such as trying to parse a CSS file as JavaScript. ## Configuration Schema If you’d like a JSON schema to validate your configuration, one is available here: [https://json.schemastore.org/prettierrc](https://json.schemastore.org/prettierrc). ## EditorConfig If a [`.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. Here’s an annotated description of how different properties map to Prettier’s behavior: ```ini # Stop the editor from looking for .editorconfig files in the parent directories # root = true [*] # Non-configurable Prettier behaviors charset = utf-8 insert_final_newline = true # Caveat: Prettier won’t trim trailing whitespace inside template strings, but your editor might. # trim_trailing_whitespace = true # Configurable Prettier behaviors # (change these if your Prettier config differs) end_of_line = lf indent_style = space indent_size = 2 max_line_length = 80 ``` Here’s a copy+paste-ready `.editorconfig` file if you use the default options: ```ini [*] charset = utf-8 insert_final_newline = true end_of_line = lf indent_style = space indent_size = 2 max_line_length = 80 ``` --- ### Editor Integration --- id: editors title: Editor Integration --- To get the most out of Prettier, it’s recommended to run it from your editor. If your editor does not support Prettier, you can instead [run Prettier with a file watcher](watching-files.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 – 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). ## Emacs Check out the [prettier-emacs](https://github.com/prettier/prettier-emacs) repo, or [prettier.el](https://github.com/jscheid/prettier.el). The package [Apheleia](https://github.com/raxod502/apheleia) supports multiple code formatters, including Prettier. ## 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). ## Helix A formatter can be specified in your [Helix language configuration](https://docs.helix-editor.com/languages.html#language-configuration), which will take precedence over any language servers. For more details see the [Helix external binary formatter configuration for Prettier](https://github.com/helix-editor/helix/wiki/External-formatter-configuration#prettier). ## Sublime Text Sublime Text support is available through Package Control and the [JsPrettier](https://packagecontrol.io/packages/JsPrettier) plug-in. ## JetBrains WebStorm, PHPStorm, PyCharm... See the [WebStorm setup guide](webstorm.md). ## Visual Studio Install the [JavaScript Prettier extension](https://github.com/madskristensen/JavaScriptPrettier). ## Espresso Espresso users can install the [espresso-prettier](https://github.com/eablokker/espresso-prettier) plugin. --- ### For Enterprise --- id: for-enterprise title: For Enterprise --- ## Available as part of the Tidelift Subscription Tidelift is working with the maintainers of Prettier and thousands of other open source projects to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more Request a demo
### Enterprise-ready open source software—managed for you The Tidelift Subscription is a managed open source subscription for application dependencies covering millions of open source projects across JavaScript, Python, Java, PHP, Ruby, .NET, and more. Your subscription includes: **Security updates** Tidelift’s security response team coordinates patches for new breaking security vulnerabilities and alerts immediately through a private channel, so your software supply chain is always secure. **Licensing verification and indemnification** Tidelift verifies license information to enable easy policy enforcement and adds intellectual property indemnification to cover creators and users in case something goes wrong. You always have a 100% up-to-date bill of materials for your dependencies to share with your legal team, customers, or partners. **Maintenance and code improvement** Tidelift ensures the software you rely on keeps working as long as you need it to work. Your managed dependencies are actively maintained and we recruit additional maintainers where required. **Package selection and version guidance** We help you choose the best open source packages from the start—and then guide you through updates to stay on the best releases as new issues arise. **Roadmap input** Take a seat at the table with the creators behind the software you use. Tidelift’s participating maintainers earn more income as their software is used by more subscribers, so they’re interested in knowing what you need. **Tooling and cloud integration** Tidelift works with GitHub, GitLab, BitBucket, and more. We support every cloud platform (and other deployment targets, too). The end result? All of the capabilities you expect from commercial-grade software, for the full breadth of open source you use. That means less time grappling with esoteric open source trivia, and more time building your own applications—and your business. Learn more Request a demo --- ### Ignoring Code --- id: ignore title: Ignoring Code --- Use `.prettierignore` to ignore (i.e. not reformat) certain files and folders completely. Use “prettier-ignore” comments to ignore parts of files. ## 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: ```text # 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! By default prettier ignores files in version control systems directories (".git", ".jj", ".sl", ".svn" and ".hg") and `node_modules` (unless the [`--with-node-modules` CLI option](cli.md#--with-node-modules) is specified). Prettier will also follow rules specified in the ".gitignore" file if it exists in the same directory from which it is run. So by default it will be ```text **/.git **/.svn **/.hg **/node_modules ``` and ```text **/.git **/.svn **/.hg ``` if [`--with-node-modules` CLI option](cli.md#--with-node-modules) provided (See also the [`--ignore-path` CLI option](cli.md#--ignore-path).) ## JavaScript A JavaScript comment of `// prettier-ignore` will exclude the next node in the abstract syntax tree from formatting. For example: ```js matrix( 1, 0, 0, 0, 1, 0, 0, 0, 1 ) // prettier-ignore matrix( 1, 0, 0, 0, 1, 0, 0, 0, 1 ) ``` will be transformed to: ```js matrix(1, 0, 0, 0, 1, 0, 0, 0, 1); // prettier-ignore matrix( 1, 0, 0, 0, 1, 0, 0, 0, 1 ) ``` ## JSX ```jsx
{/* prettier-ignore */}
``` ## HTML ```html
hello world
``` ## CSS ```css /* prettier-ignore */ .my ugly rule { } ``` ## Markdown ```markdown Do not format this ``` ### Range Ignore _available in v1.12.0+_ This type of ignore is only allowed to be used in top-level and aimed to disable formatting for auto-generated content, e.g. [`all-contributors`](https://github.com/kentcdodds/all-contributors), [`markdown-toc`](https://github.com/jonschlinkert/markdown-toc), etc. ```markdown | MY | AWESOME | AUTO-GENERATED | TABLE | |-|-|-|-| | a | b | c | d | ``` **Important:** You must have a blank line before `` and `` for Prettier to recognize the comments. ## 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 { # prettier-ignore addReaction(input:{superLongInputFieldName:"MDU6SXNzdWUyMzEzOTE1NTE=",content:HOORAY}) { reaction {content} } } ``` ## Handlebars ```hbs {{! prettier-ignore }}
"hello! my parent was ignored" {{#my-crazy-component "shall" be="preserved"}} {{/my-crazy-component}}
``` ## Command Line File Patterns For one-off commands, when you want to exclude some files without adding them to `.prettierignore`, negative patterns can come in handy: ```bash prettier . "!**/*.{js,jsx,vue}" --write ``` See [fast-glob](https://prettier.io/docs/cli#file-patterns) to learn more about advanced glob syntax. --- ### What is Prettier? --- id: index title: What is Prettier? --- Prettier is an opinionated code formatter with support for: - JavaScript (including experimental features) - [JSX](https://facebook.github.io/jsx/) - [Angular](https://angular.dev/) - [Vue](https://vuejs.org/) - [Flow](https://flow.org/) - [TypeScript](https://www.typescriptlang.org/) - CSS, [Less](https://lesscss.org/), and [SCSS](https://sass-lang.com) - [HTML](https://en.wikipedia.org/wiki/HTML) - [Ember/Handlebars](https://handlebarsjs.com/) - [JSON](https://json.org/) - [GraphQL](https://graphql.org/) - [Markdown](https://commonmark.org/), including [GFM](https://github.github.com/gfm/) and [MDX v1](https://mdxjs.com/) - [YAML](https://yaml.org/) It removes all original styling[\*](#footnotes) and ensures that all outputted code conforms to a consistent style. (See this [blog post](https://jlongster.com/A-Prettier-Formatter)) Prettier takes your code and reprints it from scratch by taking the line length into account. For example, take the following code: ```js foo(arg1, arg2, arg3, arg4); ``` It fits in a single line so it’s going to stay as is. However, we've all run into this situation: ```js foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne()); ``` Suddenly our previous format for calling function breaks down because this is too long. Prettier is going to do the painstaking work of reprinting it like that for you: ```js foo( reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne(), ); ``` Prettier enforces a consistent code **style** (i.e. code formatting that won’t affect the AST) across your entire codebase because it disregards the original styling[\*](#footnotes) by parsing it away and re-printing the parsed AST with its own rules that take the maximum line length into account, wrapping code when necessary. If you want to learn more, these two conference talks are great introductions: [![A Prettier Printer by James Long on React Conf 2017](/images/youtube-cover/a-prettier-printer-by-james-long-on-react-conf-2017.png)](https://www.youtube.com/watch?v=hkfBvpEfWdA) [![JavaScript Code Formatting by Christopher Chedeau on React London 2017](/images/youtube-cover/javascript-code-formatting-by-christopher-chedeau-on-react-london-2017.png)](https://www.youtube.com/watch?v=0Q4kUNx85_4) #### Footnotes \* _Well actually, some original styling is preserved when practical—see [empty lines](rationale.md#empty-lines) and [multi-line objects](rationale.md#multi-line-objects)._ --- ### Install --- id: install title: Install --- import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; First, install Prettier locally: ```bash npm install --save-dev --save-exact prettier ``` ```bash yarn add --dev --exact prettier ``` ```bash pnpm add --save-dev --save-exact prettier ``` ```bash bun add --dev --exact prettier ``` Then, create an empty config file to let editors and other tools know you are using Prettier: ```bash node --eval "fs.writeFileSync('.prettierrc','{}\n')" ``` Next, create a [.prettierignore](ignore.md) file to let the Prettier CLI and editors know which files to _not_ format. Here’s an example: ```bash node --eval "fs.writeFileSync('.prettierignore','# Ignore artifacts:\nbuild\ncoverage\n')" ``` :::tip Prettier will follow rules specified in .gitignore if it exists in the same directory from which it is run. You can also base your .prettierignore on .eslintignore (if you have one). ::: :::tip[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 ``` :::info 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! ::: :::warning 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 exec prettier . --write ``` :::info What is `yarn exec` doing at the start? `yarn exec prettier` runs the locally installed version of Prettier. We’ll leave off the `yarn exec` part for brevity throughout the rest of this file! ::: ```bash pnpm exec prettier . --write ``` :::info What is `pnpm exec` doing at the start? `pnpm exec prettier` runs the locally installed version of Prettier. We’ll leave off the `pnpm exec` part for brevity throughout the rest of this file! ::: ```bash bun exec prettier . --write ``` :::info What is `bun exec` doing at the start? `bun exec prettier` runs the locally installed version of Prettier. We’ll leave off the `bun exec` 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 npx 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 do the following to have Prettier run before each commit: 1. Install [husky](https://github.com/typicode/husky) and [lint-staged](https://github.com/okonet/lint-staged): ```bash npm install --save-dev husky lint-staged npx husky init node --eval "fs.writeFileSync('.husky/pre-commit','npx lint-staged\n')" ``` ```bash yarn add --dev husky lint-staged npx husky init node --eval "fs.writeFileSync('.husky/pre-commit','yarn lint-staged\n')" ``` :::note If you use Yarn 2, see https://typicode.github.io/husky/#/?id=yarn-2 ::: ```bash pnpm add --save-dev husky lint-staged pnpm exec husky init node --eval "fs.writeFileSync('.husky/pre-commit','pnpm exec lint-staged\n')" ``` ```bash bun add --dev husky lint-staged bunx husky init bun --eval "fs.writeFileSync('.husky/pre-commit','bunx lint-staged\n')" ``` 2. Add the following to your `package.json`: ```json { "lint-staged": { "**/*": "prettier --write --ignore-unknown" } } ``` :::note If you use ESLint, make sure lint-staged runs it before Prettier, not after. ::: 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` 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. --- ### Integrating with Linters --- id: integrating-with-linters title: Integrating with Linters --- 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). Luckily it’s easy to turn off rules that conflict or are unnecessary with Prettier, by using these pre-made configs: - [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) Check out the above links for instructions on how to install and set things up. ## Notes 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. First, we have plugins that let you run Prettier as if it was a linter rule: - [eslint-plugin-prettier](https://github.com/prettier/eslint-plugin-prettier) - [stylelint-prettier](https://github.com/prettier/stylelint-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. The downsides of those plugins are: - 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. Finally, we have tools that run `prettier` and then immediately lint files by running, for example, `eslint --fix` on them. - [prettier-eslint](https://github.com/prettier/prettier-eslint) - [prettier-stylelint](https://github.com/hugomrdias/prettier-stylelint) 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. --- ### Option Philosophy --- id: option-philosophy title: Option Philosophy --- :::info Prettier has a few options because of history. **But we won’t add more of them.** Read on to learn more. ::: Prettier is not a kitchen-sink code formatter that attempts to print your code in any way you wish. It is _opinionated._ Quoting the [Why Prettier?](why-prettier.md) page: > By far the biggest reason for adopting Prettier is to stop all the ongoing debates over styles. Yet the more options Prettier has, the further from the above goal it gets. **The debates over styles just turn into debates over which Prettier options to use.** Formatting wars break out with renewed vigour: “Which option values are better? Why? Did we make the right choices?” And it’s not the only cost options have. To learn more about their downsides, see the [issue about resisting adding configuration](https://github.com/prettier/prettier/issues/40), which has more 👍s than any option request issue. So why are there any options at all? - A few were added during Prettier’s infancy to make it take off at all. 🚀 - A couple were added after “great demand.” 🤔 - Some were added for compatibility reasons. 👍 Options that are easier to motivate include: - `--trailing-comma es5` lets you use trailing commas in most environments without having to transpile (trailing function commas were added in ES2017). - `--prose-wrap` is important to support all quirky Markdown renderers in the wild. - `--html-whitespace-sensitivity` is needed due to the unfortunate whitespace rules of HTML. - `--end-of-line` makes it easier for teams to keep CRLFs out of their git repositories. - `--quote-props` is important for advanced usage of the Google Closure Compiler. But other options are harder to motivate in hindsight: `--arrow-parens`, `--jsx-single-quote`, `--bracket-same-line` and `--no-bracket-spacing` are not the type of options we’re happy to have. They cause a lot of [bike-shedding](https://en.wikipedia.org/wiki/Law_of_triviality) in teams, and we’re sorry for that. Difficult to remove now, these options exist as a historical artifact and should not motivate adding more options (“If _those_ options exist, why can’t this one?”). For a long time, we left option requests open in order to let discussions play out and collect feedback. What we’ve learned during those years is that it’s really hard to measure demand. Prettier has grown a lot in usage. What was “great demand” back in the day is not as much today. GitHub reactions and Twitter polls became unrepresentative. What about all silent users? It looked easy to add “just one more” option. But where should we have stopped? When is one too many? Even after adding “that one final option”, there would always be a “top issue” in the issue tracker. However, the time to stop has come. Now that Prettier is mature enough and we see it adopted by so many organizations and projects, the research phase is over. We have enough confidence to conclude that Prettier reached a point where the set of options should be “frozen”. **Option requests aren’t accepted anymore.** We’re thankful to everyone who participated in this difficult journey. Please note that as option requests are out of scope for Prettier, they will be closed without discussion. The same applies to requests to preserve elements of input formatting (e.g. line breaks) since that’s nothing else but an option in disguise with all the downsides of “real” options. There may be situations where adding an option can’t be avoided because of technical necessity (e.g. compatibility), but for formatting-related options, this is final. --- ### Options --- id: options title: Options --- 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. ## Experimental Ternaries Try prettier's [new ternary formatting](https://github.com/prettier/prettier/pull/13183) before it becomes the default behavior. Valid options: - `true` - Use curious ternaries, with the question mark after the condition. - `false` - Retain the default behavior of ternaries; keep question marks on the same line as the consequent. | Default | CLI Override | API Override | | ------- | -------------------------- | ------------------------------- | | `false` | `--experimental-ternaries` | `experimentalTernaries: ` | ## Experimental Operator Position Valid options: - `"start"` - When binary expressions wrap lines, print operators at the start of new lines. - `"end"` - Default behavior; when binary expressions wrap lines, print operators at the end of previous lines. | Default | CLI Override | API Override | | ------- | --------------------------------------------------------------- | -------------------------------------------------------------- | | `"end"` | --experimental-operator-position \ | experimentalOperatorPosition: "\" | ## Print Width Specify the line length that the printer will wrap on. :::warning **For readability we recommend against using more than 80 characters:** In code styleguides, maximum line length rules are often set to 100 or 120. However, when humans write code, they don’t strive to reach the maximum number of columns on every line. Developers often use whitespace to break up long lines for readability. In practice, the average line length often ends up well below the maximum. Prettier’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. 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: ` | Setting `max_line_length` in an [`.editorconfig` file](https://editorconfig.org/) will configure Prettier’s print width, unless overridden. (If you don’t want line wrapping when formatting Markdown, you can set the [Prose Wrap](#prose-wrap) option to disable it.) ## Tab Width Specify the number of spaces per indentation-level. | Default | CLI Override | API Override | | ------- | ------------------- | ----------------- | | `2` | `--tab-width ` | `tabWidth: ` | Setting `indent_size` or `tab_width` in an [`.editorconfig` file](https://editorconfig.org/) will configure Prettier’s tab width, unless overridden. ## Tabs Indent lines with tabs instead of spaces. | Default | CLI Override | API Override | | ------- | ------------ | ----------------- | | `false` | `--use-tabs` | `useTabs: ` | Setting `indent_style` in an [`.editorconfig` file](https://editorconfig.org/) will configure Prettier’s tab usage, unless overridden. (Tabs will be used for _indentation_ but Prettier uses spaces to _align_ things, such as in ternaries. This behavior is known as [SmartTabs](https://www.emacswiki.org/emacs/SmartTabs).) ## Semicolons Print semicolons at the ends of statements. Valid options: - `true` - Add a semicolon at the end of every statement. - `false` - Only add semicolons at the beginning of lines that [may introduce ASI failures](rationale.md#semicolons). | Default | CLI Override | API Override | | ------- | ------------ | -------------- | | `true` | `--no-semi` | `semi: ` | ## Quotes Use single quotes instead of double quotes. Notes: - JSX quotes ignore this option – see [jsx-single-quote](#jsx-quotes). - If the number of quotes outweighs the other quote, the quote which is less used will be used to format the string - Example: `"I'm double quoted"` results in `"I'm double quoted"` and `"This \"example\" is single quoted"` results in `'This "example" is single quoted'`. See the [strings rationale](rationale.md#strings) for more information. | Default | CLI Override | API Override | | ------- | ---------------- | --------------------- | | `false` | `--single-quote` | `singleQuote: ` | ## Quote Props Change when properties in objects are quoted. Valid options: - `"as-needed"` - Only add quotes around object properties where required. - `"consistent"` - If at least one property in an object requires quotes, quote all properties. - `"preserve"` - Respect the input use of quotes in object properties. | Default | CLI Override | API Override | | ------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- | | `"as-needed"` | --quote-props \ | quoteProps: "\" | Note that Prettier never unquotes numeric property names in Angular expressions, TypeScript, and Flow because the distinction between string and numeric keys is significant in these languages. See: [Angular][quote-props-angular], [TypeScript][quote-props-typescript], [Flow][quote-props-flow]. Also Prettier doesn’t unquote numeric properties for Vue (see the [issue][quote-props-vue] about that). [quote-props-angular]: https://codesandbox.io/s/hungry-morse-foj87?file=/src/app/app.component.html [quote-props-typescript]: https://www.typescriptlang.org/play?#code/DYUwLgBAhhC8EG8IEYBcKA0EBM7sQF8AoUSAIzkQgHJlr1ktrt6dCiiATEAY2CgBOICKWhR0AaxABPAPYAzCGGkAHEAugBuLr35CR4CGTKSZG5Wo1ltRKDHjHtQA [quote-props-flow]: https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVBjOA7AzgFzAA8wBeMAb1TDAAYAuMARlQF8g [quote-props-vue]: https://github.com/prettier/prettier/issues/10127 ## JSX Quotes Use single quotes instead of double quotes in JSX. | Default | CLI Override | API Override | | ------- | -------------------- | ------------------------ | | `false` | `--jsx-single-quote` | `jsxSingleQuote: ` | ## Trailing Commas _Default value changed from `es5` to `all` in v3.0.0_ Print trailing commas wherever possible in multi-line comma-separated syntactic structures. (A single-line array, for example, never gets trailing commas.) Valid options: - `"all"` - Trailing commas wherever possible (including [function parameters and calls](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Trailing_commas#Trailing_commas_in_functions)). To run, JavaScript code formatted this way needs an engine that supports ES2017 (Node.js 8+ or a modern browser) or [downlevel compilation](https://babeljs.io/docs/index). This also enables trailing commas in type parameters in TypeScript (supported since TypeScript 2.7 released in January 2018). - `"es5"` - Trailing commas where valid in ES5 (objects, arrays, etc.). Trailing commas in type parameters in TypeScript and Flow. - `"none"` - No trailing commas. | Default | CLI Override | API Override | | ------- | ------------------------------------------------------- | ------------------------------------------------------- | | `"all"` | --trailing-comma \ | trailingComma: "\" | ## Bracket Spacing Print spaces between brackets in object literals. Valid options: - `true` - Example: `{ foo: bar }`. - `false` - Example: `{foo: bar}`. | Default | CLI Override | API Override | | ------- | ---------------------- | ------------------------ | | `true` | `--no-bracket-spacing` | `bracketSpacing: ` | ## Object Wrap _First available in v3.5.0_ Configure how Prettier wraps object literals when they could fit on one line or span multiple lines. By default, Prettier formats objects as multi-line if there is a newline prior to the first property. Authors can use this heuristic to contextually improve readability, though it has some downsides. See [Multi-line objects](rationale.md#multi-line-objects). Valid options: - `"preserve"` - Keep as multi-line, if there is a newline between the opening brace and first property. - `"collapse"` - Fit to a single line when possible. | Default | CLI Override | API Override | | ------------ | ---------------------------------------------------- | ---------------------------------------------------- | | `"preserve"` | --object-wrap \ | objectWrap: "\" | ## Bracket Line Put the `>` of a multi-line HTML (HTML, JSX, Vue, Angular) element at the end of the last line instead of being alone on the next line (does not apply to self closing elements). Valid options: - `true` - Example: ```html ``` - `false` - Example: ```html ``` | Default | CLI Override | API Override | | ------- | --------------------- | ------------------------- | | `false` | `--bracket-same-line` | `bracketSameLine: ` | ## [Deprecated] JSX Brackets :::danger This option has been deprecated in v2.4.0, use --bracket-same-line instead. ::: Put the `>` of a multi-line JSX element at the end of the last line instead of being alone on the next line (does not apply to self closing elements). Valid options: - `true` - Example: ```jsx ``` - `false` - Example: ```jsx ``` | Default | CLI Override | API Override | | ------- | ------------------------- | ---------------------------- | | `false` | `--jsx-bracket-same-line` | `jsxBracketSameLine: ` | ## Arrow Function Parentheses _First available in v1.9.0, default value changed from `avoid` to `always` in v2.0.0_ Include parentheses around a sole arrow function parameter. Valid options: - `"always"` - Always include parens. Example: `(x) => x` - `"avoid"` - Omit parens when possible. Example: `x => x` | Default | CLI Override | API Override | | ---------- | ------------------------------------------------ | ------------------------------------------------ | | `"always"` | --arrow-parens \ | arrowParens: "\" | At first glance, avoiding parentheses may look like a better choice because of less visual noise. However, when Prettier removes parentheses, it becomes harder to add type annotations, extra arguments or default values as well as making other changes. Consistent use of parentheses provides a better developer experience when editing real codebases, which justifies the default value for the option. ## Range Format only a segment of a file. These two options can be used to format code starting and ending at a given character offset (inclusive and exclusive, respectively). The range will extend: - Backwards to the start of the first line containing the selected statement. - Forwards to the end of the selected statement. | Default | CLI Override | API Override | | ---------- | --------------------- | ------------------- | | `0` | `--range-start ` | `rangeStart: ` | | `Infinity` | `--range-end ` | `rangeEnd: ` | ## Parser Specify which parser to use. Prettier automatically infers the parser from the input file path, so you shouldn’t have to change this setting. Both the `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: - `"babel"` (via [@babel/parser](https://github.com/babel/babel/tree/main/packages/babel-parser)) _Named `"babylon"` until v1.16.0_ - `"babel-flow"` (same as `"babel"` but enables Flow parsing explicitly to avoid ambiguity) _First available in v1.16.0_ - `"babel-ts"` (similar to `"typescript"` but uses Babel and its TypeScript plugin) _First available in v2.0.0_ - `"flow"` (via [flow-parser](https://github.com/facebook/flow/tree/master/src/parser)) - `"typescript"` (via [@typescript-eslint/typescript-estree](https://github.com/typescript-eslint/typescript-eslint)) _First available in v1.4.0_ - `"espree"` (via [espree](https://github.com/eslint/espree)) _First available in v2.2.0_ - `"meriyah"` (via [meriyah](https://github.com/meriyah/meriyah)) _First available in v2.2.0_ - `"acorn"` (via [acorn](https://github.com/acornjs/acorn)) _First available in v2.6.0_ - `"css"` (via [postcss](https://github.com/postcss/postcss)) _First available in v1.7.1_ - `"scss"` (via [postcss-scss](https://github.com/postcss/postcss-scss)) _First available in v1.7.1_ - `"less"` (via [postcss-less](https://github.com/shellscape/postcss-less)) _First available in v1.7.1_ - `"json"` (via [@babel/parser parseExpression](https://babeljs.io/docs/babel-parser#babelparserparseexpressioncode-options)) _First available in v1.5.0_ - `"json5"` (same parser as `"json"`, but outputs as [json5](https://json5.org/)) _First available in v1.13.0_ - `"jsonc"` (same parser as `"json"`, but outputs as "JSON with Comments") _First available in v3.2.0_ - `"json-stringify"` (same parser as `"json"`, but outputs like `JSON.stringify`) _First available in v1.13.0_ - `"graphql"` (via [graphql/language](https://github.com/graphql/graphql-js/tree/master/src/language)) _First available in v1.5.0_ - `"markdown"` (via [remark-parse](https://github.com/wooorm/remark/tree/main/packages/remark-parse)) _First available in v1.8.0_ - `"mdx"` (via [remark-parse](https://github.com/wooorm/remark/tree/main/packages/remark-parse) and [@mdx-js/mdx](https://github.com/mdx-js/mdx/tree/master/packages/mdx)) _First available in v1.15.0_ - `"html"` (via [angular-html-parser](https://github.com/ikatyang/angular-html-parser/tree/master/packages/angular-html-parser)) _First available in 1.15.0_ - `"vue"` (same parser as `"html"`, but also formats vue-specific syntax) _First available in 1.10.0_ - `"angular"` (same parser as `"html"`, but also formats angular-specific syntax via [angular-estree-parser](https://github.com/ikatyang/angular-estree-parser)) _First available in 1.15.0_ - `"lwc"` (same parser as `"html"`, but also formats LWC-specific syntax for unquoted template attributes) _First available in 1.17.0_ - `"yaml"` (via [yaml](https://github.com/eemeli/yaml) and [yaml-unist-parser](https://github.com/ikatyang/yaml-unist-parser)) _First available in 1.14.0_ | Default | CLI Override | API Override | | ------- | ------------------- | -------------------- | | None | `--parser ` | `parser: ""` | Note: the default value was `"babylon"` until v1.13.0. Note: the Custom parser API has been removed in v3.0.0. Use [plugins](plugins.md) instead ([how to migrate](api.md#custom-parser-api-removed)). ## File Path Specify the file name to use to infer which parser to use. For example, the following will use the CSS parser: ```bash cat foo | prettier --stdin-filepath foo.css ``` 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 _First available in v1.7.0_ Prettier can restrict itself to only format files that contain a special comment, called a pragma, at the top of the file. This is very useful when gradually transitioning large, unformatted codebases to Prettier. A file with the following as its first comment will be formatted when `--require-pragma` is supplied: ```js /** * @prettier */ ``` or ```js /** * @format */ ``` | Default | CLI Override | API Override | | ------- | ------------------ | ----------------------- | | `false` | `--require-pragma` | `requirePragma: ` | ## Insert Pragma _First available in v1.8.0_ Prettier can insert a special `@format` marker at the top of files specifying that the file has been formatted with Prettier. This works well when used in tandem with the `--require-pragma` option. If there is already a docblock at the top of the file then this option will add a newline to it with the `@format` marker. Note that “in tandem” doesn’t mean “at the same time”. When the two options are used simultaneously, `--require-pragma` has priority, so `--insert-pragma` is ignored. The idea is that during an incremental adoption of Prettier in a big codebase, the developers participating in the transition process use `--insert-pragma` whereas `--require-pragma` is used by the rest of the team and automated tooling to process only files already transitioned. The feature has been inspired by Facebook’s [adoption strategy]. | Default | CLI Override | API Override | | ------- | ----------------- | ---------------------- | | `false` | `--insert-pragma` | `insertPragma: ` | [adoption strategy]: https://prettier.io/blog/2017/05/03/1.3.0.html#facebook-adoption-update ## Prose Wrap _First available in v1.8.2_ By default, Prettier will not change wrapping in markdown text since some services use a linebreak-sensitive renderer, e.g. GitHub comments and BitBucket. To have Prettier wrap prose to the print width, change this option to "always". If you want Prettier to force all prose blocks to be on a single line and rely on editor/viewer soft wrapping instead, you can use `"never"`. Valid options: - `"always"` - Wrap prose if it exceeds the print width. - `"never"` - Un-wrap each block of prose into one line. - `"preserve"` - Do nothing, leave prose as-is. _First available in v1.9.0_ | Default | CLI Override | API Override | | ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | | `"preserve"` | --prose-wrap \ | proseWrap: "\" | ## HTML Whitespace Sensitivity _First available in v1.15.0. First available for Handlebars in 2.3.0_ Specify the global whitespace sensitivity for HTML, Vue, Angular, and Handlebars. See [whitespace-sensitive formatting] for more info. [whitespace-sensitive formatting]: https://prettier.io/blog/2018/11/07/1.15.0.html#whitespace-sensitive-formatting Valid options: - `"css"` - Respect the default value of CSS `display` property. For Handlebars treated same as `strict`. - `"strict"` - Whitespace (or the lack of it) around all tags is considered significant. - `"ignore"` - Whitespace (or the lack of it) around all tags is considered insignificant. | Default | CLI Override | API Override | | ------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------ | | `"css"` | --html-whitespace-sensitivity \ | htmlWhitespaceSensitivity: "\" | ## Vue files script and style tags indentation _First available in v1.19.0_ Whether or not to indent the code inside `", ]; }; } } ``` If the [`--embedded-language-formatting`](options.md#embedded-language-formatting) option is set to `off`, the embedding step is entirely skipped, `embed` isn’t called, and all nodes are printed with the `print` method. #### (optional) `preprocess` The `preprocess` method can process the AST from the parser before passing it into the `print` method. ```ts function preprocess(ast: AST, options: Options): AST | Promise; ``` #### (optional) `getVisitorKeys` This property might come in handy if the plugin uses comment attachment or embedded languages. These features traverse the AST iterating through all the own enumerable properties of each node starting from the root. If the AST has [cycles](), such a traverse ends up in an infinite loop. Also, nodes might contain non-node objects (e.g., location data), iterating through which is a waste of resources. To solve these issues, the printer can define a function to return property names that should be traversed. Its signature is: ```ts function getVisitorKeys(node, nonTraversableKeys: Set): string[]; ``` The default `getVisitorKeys`: ```js function getVisitorKeys(node, nonTraversableKeys) { return Object.keys(node).filter((key) => !nonTraversableKeys.has(key)); } ``` The second argument `nonTraversableKeys` is a set of common keys and keys that prettier used internal. If you have full list of visitor keys ```js const visitorKeys = { Program: ["body"], Identifier: [], // ... }; function getVisitorKeys(node /* , nonTraversableKeys*/) { // Return `[]` for unknown node to prevent Prettier fallback to use `Object.keys()` return visitorKeys[node.type] ?? []; } ``` If you only need exclude a small set of keys ```js const ignoredKeys = new Set(["prev", "next", "range"]); function getVisitorKeys(node, nonTraversableKeys) { return Object.keys(node).filter( (key) => !nonTraversableKeys.has(key) && !ignoredKeys.has(key), ); } ``` #### (optional) `insertPragma` A plugin can implement how a pragma comment is inserted in the resulting code when the `--insert-pragma` option is used, in the `insertPragma` function. Its signature is: ```ts function insertPragma(text: string): string; ``` #### Handling comments in a printer Comments are often not part of a language's AST and present a challenge for pretty printers. A Prettier plugin can either print comments itself in its `print` function or rely on Prettier's comment algorithm. By default, if the AST has a top-level `comments` property, Prettier assumes that `comments` stores an array of comment nodes. Prettier will then use the provided `parsers[].locStart`/`locEnd` functions to search for the AST node that each comment "belongs" to. Comments are then attached to these nodes **mutating the AST in the process**, and the `comments` property is deleted from the AST root. The `*Comment` functions are used to adjust Prettier's algorithm. Once the comments are attached to the AST, Prettier will automatically call the `printComment(path, options): Doc` function and insert the returned doc into the (hopefully) correct place. #### (optional) `getCommentChildNodes` By default, Prettier searches all object properties (except for a few predefined ones) of each node recursively. This function can be provided to override that behavior. It has the signature: ```ts function getCommentChildNodes( // The node whose children should be returned. node: AST, // Current options options: object, ): AST[] | undefined; ``` Return `[]` if the node has no children or `undefined` to fall back on the default behavior. #### (optional) `printComment` Called whenever a comment node needs to be printed. It has the signature: ```ts function printComment( // Path to the current comment node commentPath: AstPath, // Current options options: object, ): Doc; ``` #### (optional) `canAttachComment` ```ts function canAttachComment(node: AST): boolean; ``` This function is used for deciding whether a comment can be attached to a particular AST node. By default, _all_ AST properties are traversed searching for nodes that comments can be attached to. This function is used to prevent comments from being attached to a particular node. A typical implementation looks like ```js function canAttachComment(node) { return node.type && node.type !== "comment"; } ``` #### (optional) `isBlockComment` ```ts function isBlockComment(node: AST): boolean; ``` Returns whether or not the AST node is a block comment. #### (optional) `handleComments` The `handleComments` object contains three optional functions, each with signature ```ts ( // The AST node corresponding to the comment comment: AST, // The full source code text text: string, // The global options object options: object, // The AST ast: AST, // Whether this comment is the last comment isLastComment: boolean, ) => boolean; ``` These functions are used to override Prettier's default comment attachment algorithm. `ownLine`/`endOfLine`/`remaining` is expected to either manually attach a comment to a node and return `true`, or return `false` and let Prettier attach the comment. Based on the text surrounding a comment node, Prettier dispatches: - `ownLine` if a comment has only whitespace preceding it and a newline afterwards, - `endOfLine` if a comment has a newline afterwards but some non-whitespace preceding it, - `remaining` in all other cases. At the time of dispatching, Prettier will have annotated each AST comment node (i.e., created new properties) with at least one of `enclosingNode`, `precedingNode`, or `followingNode`. These can be used to aid a plugin's decision process (of course the entire AST and original text is also passed in for making more complicated decisions). #### Manually attaching a comment The `util.addTrailingComment`/`addLeadingComment`/`addDanglingComment` functions can be used to manually attach a comment to an AST node. An example `ownLine` function that ensures a comment does not follow a "punctuation" node (made up for demonstration purposes) might look like: ```js import { util } from "prettier"; function ownLine(comment, text, options, ast, isLastComment) { const { precedingNode } = comment; if (precedingNode && precedingNode.type === "punctuation") { util.addTrailingComment(precedingNode, comment); return true; } return false; } ``` Nodes with comments are expected to have a `comments` property containing an array of comments. Each comment is expected to have the following properties: `leading`, `trailing`, `printed`. The example above uses `util.addTrailingComment`, which automatically sets `comment.leading`/`trailing`/`printed` to appropriate values and adds the comment to the AST node's `comments` array. The `--debug-print-comments` CLI flag can help with debugging comment attachment issues. It prints a detailed list of comments, which includes information on how every comment was classified (`ownLine`/`endOfLine`/`remaining`, `leading`/`trailing`/`dangling`) and to which node it was attached. For Prettier’s built-in languages, this information is also available on the Playground (the 'show comments' checkbox in the Debug section). ### `options` `options` is an object containing the custom options your plugin supports. Example: ```js export default { // ... plugin implementation options: { openingBraceNewLine: { type: "boolean", category: "Global", default: true, description: "Move open brace for code blocks onto new line.", }, }, }; ``` ### `defaultOptions` If your plugin requires different default values for some of Prettier’s core options, you can specify them in `defaultOptions`: ```js export default { // ... plugin implementation defaultOptions: { tabWidth: 4, }, }; ``` ### Utility functions A `util` module from Prettier core is considered a private API and is not meant to be consumed by plugins. Instead, the `util-shared` module provides the following limited set of utility functions for plugins: ```ts type Quote = '"' | "'"; type SkipOptions = { backwards?: boolean }; function getMaxContinuousCount(text: string, searchString: string): number; function getStringWidth(text: string): number; function getAlignmentSize( text: string, tabWidth: number, startIndex?: number, ): number; function getIndentSize(value: string, tabWidth: number): number; function skip( characters: string | RegExp, ): ( text: string, startIndex: number | false, options?: SkipOptions, ) => number | false; function skipWhitespace( text: string, startIndex: number | false, options?: SkipOptions, ): number | false; function skipSpaces( text: string, startIndex: number | false, options?: SkipOptions, ): number | false; function skipToLineEnd( text: string, startIndex: number | false, options?: SkipOptions, ): number | false; function skipEverythingButNewLine( text: string, startIndex: number | false, options?: SkipOptions, ): number | false; function skipInlineComment( text: string, startIndex: number | false, ): number | false; function skipTrailingComment( text: string, startIndex: number | false, ): number | false; function skipNewline( text: string, startIndex: number | false, options?: SkipOptions, ): number | false; function hasNewline( text: string, startIndex: number, options?: SkipOptions, ): boolean; function hasNewlineInRange( text: string, startIndex: number, startIndex: number, ): boolean; function hasSpaces( text: string, startIndex: number, options?: SkipOptions, ): boolean; function getPreferredQuote( text: string, preferredQuoteOrPreferSingleQuote: Quote | boolean, ): Quote; function makeString( rawText: string, enclosingQuote: Quote, unescapeUnnecessaryEscapes?: boolean, ): string; function getNextNonSpaceNonCommentCharacter( text: string, startIndex: number, ): string; function getNextNonSpaceNonCommentCharacterIndex( text: string, startIndex: number, ): number | false; function isNextLineEmpty(text: string, startIndex: number): boolean; function isPreviousLineEmpty(text: string, startIndex: number): boolean; ``` ### Tutorials - [How to write a plugin for Prettier](https://medium.com/@fvictorio/how-to-write-a-plugin-for-prettier-a0d98c845e70): Teaches you how to write a very basic Prettier plugin for TOML. ## Testing Plugins Since plugins can be resolved using relative paths, when working on one you can do: ```js import * as prettier from "prettier"; const code = "(add 1 2)"; await prettier.format(code, { parser: "lisp", plugins: ["."], }); ``` This will resolve a plugin relative to the current working directory. --- ### Pre-commit Hook --- id: precommit title: Pre-commit Hook --- import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; You can use Prettier with a pre-commit tool. This can re-format your files that are marked as “staged” via `git add` before you commit. ## Option 1. [lint-staged](https://github.com/okonet/lint-staged) **Use Case:** Useful for when you want to use other code quality tools along with Prettier (e.g. ESLint, Stylelint, etc.) or if you need support for partially staged files (`git add --patch`). _Make sure Prettier is installed and is in your [`devDependencies`](https://docs.npmjs.com/specifying-dependencies-and-devdependencies-in-a-package-json-file) before you proceed._ ```bash npx mrm@2 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. Read more at the [lint-staged](https://github.com/okonet/lint-staged#configuration) repo. ## Option 2. [pretty-quick](https://github.com/prettier/pretty-quick) **Use Case:** Great for when you want an entire file formatting on your changed/staged files. Install it along with [simple-git-hooks](https://github.com/toplenboren/simple-git-hooks): ```bash npm install --save-dev simple-git-hooks pretty-quick echo '{\n "pre-commit": "npx pretty-quick --staged"\n}\n' > .simple-git-hooks.json npx simple-git-hooks ``` ```bash yarn add --dev simple-git-hooks pretty-quick echo '{\n "pre-commit": "yarn pretty-quick --staged"\n}\n' > .simple-git-hooks.json yarn simple-git-hooks ``` ```bash pnpm add --save-dev simple-git-hooks pretty-quick echo '{\n "pre-commit": "pnpm pretty-quick --staged"\n}\n' > .simple-git-hooks.json pnpm simple-git-hooks ``` ```bash bun add --dev simple-git-hooks pretty-quick echo '{\n "pre-commit": "bun pretty-quick --staged"\n}\n' > .simple-git-hooks.json bun simple-git-hooks ``` Read more at the [pretty-quick](https://github.com/prettier/pretty-quick) repo. ## Option 3. [Husky.Net](https://github.com/alirezanet/Husky.Net) **Use Case:** A dotnet solution to use Prettier along with other code quality tools (e.g. dotnet-format, ESLint, Stylelint, etc.). It supports multiple file states (staged - last-commit, git-files etc.) ```bash dotnet new tool-manifest dotnet tool install husky dotnet husky install dotnet husky add pre-commit ``` after installation you can add prettier task to the `task-runner.json`. ```json { "command": "npx", "args": ["prettier", "--ignore-unknown", "--write", "${staged}"], "pathMode": "absolute" } ``` ## Option 4. [git-format-staged](https://github.com/hallettj/git-format-staged) **Use Case:** Great for when you want to format partially-staged files, and other options do not provide a good fit for your project. Git-format-staged is used to run any formatter that can accept file content via stdin. It operates differently than other tools that format partially-staged files: it applies the formatter directly to objects in the git object database, and merges changes back to the working tree. This procedure provides several guarantees: 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. 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 npx husky init npm install --save-dev git-format-staged node --eval "fs.writeFileSync('.husky/pre-commit', 'git-format-staged -f \'prettier --ignore-unknown --stdin --stdin-filepath \"{}\"\' .\n')" ``` ```bash yarn husky init yarn add --dev git-format-staged node --eval "fs.writeFileSync('.husky/pre-commit', 'git-format-staged -f \'prettier --ignore-unknown --stdin --stdin-filepath \"{}\"\' .\n')" ``` ```bash pnpm exec husky init pnpm add --save-dev git-format-staged node --eval "fs.writeFileSync('.husky/pre-commit', 'git-format-staged -f \'prettier --ignore-unknown --stdin --stdin-filepath \"{}\"\' .\n')" ``` ```bash bunx husky init bun add --dev git-format-staged bun --eval "fs.writeFileSync('.husky/pre-commit', 'git-format-staged -f \'prettier --ignore-unknown --stdin --stdin-filepath \"{}\"\' .\n')" ``` Add or remove file extensions to suit your project. Note that regardless of which extensions you list formatting will respect any `.prettierignore` files in your project. 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 5. Shell script Alternately you can save this script as `.git/hooks/pre-commit` and give it execute permission: ```sh #!/bin/sh FILES=$(git diff --cached --name-only --diff-filter=ACMR | sed 's| |\\ |g') [ -z "$FILES" ] && exit 0 # Prettify all selected files echo "$FILES" | xargs ./node_modules/.bin/prettier --ignore-unknown --write # Add back the modified/prettified files to staging 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](https://github.com/prettier/prettier/issues/2978#issuecomment-334408427). Add something like the following to `.git/hooks/post-commit`: ```sh #!/bin/sh git update-index -g ``` --- ### Rationale --- id: rationale title: Rationale --- Prettier is an opinionated code formatter. This document explains some of its choices. ## What Prettier is concerned about ### Correctness The first requirement of Prettier is to output valid code that has the exact same behavior as before formatting. Please report any code where Prettier fails to follow these correctness rules — that’s a bug which needs to be fixed! ### Strings Double or single quotes? Prettier chooses the one which results in the fewest number of escapes. `"It's gettin' better!"`, not `'It\'s gettin\' better!'`. In case of a tie or the string not containing any quotes, Prettier defaults to double quotes (but that can be changed via the [singleQuote](/docs/options#quotes) option). JSX has its own option for quotes: [jsxSingleQuote](/docs/options#jsx-quotes). JSX takes its roots from HTML, where the dominant use of quotes for attributes is double quotes. Browser developer tools also follow this convention by always displaying HTML with double quotes, even if the source code uses single quotes. A separate option allows using single quotes for JS and double quotes for "HTML" (JSX). Prettier maintains the way your string is escaped. For example, `"🙂"` won’t be formatted into `"\uD83D\uDE42"` and vice versa. ### Empty lines It turns out that empty lines are very hard to automatically generate. The approach that Prettier takes is to preserve empty lines the way they were in the original source code. There are two additional rules: - Prettier collapses multiple blank lines into a single blank line. - Empty lines at the start and end of blocks (and whole files) are removed. (Files always end with a single newline, though.) ### Multi-line objects By default, 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 by default Prettier keeps objects multi-line if there’s a newline between the `{` and the first key in the original source code. Consequently, long single-line objects are automatically expanded, but short multi-line objects are never collapsed. You can disable this conditional behavior with the [`objectWrap`](options.md#object-wrap) option. **Tip:** If you have a multi-line object that you’d like to join up into a single line: ```js const user = { name: "John Doe", age: 30, }; ``` …all you need to do is remove the newline after `{`: ```js const user = { name: "John Doe", age: 30 }; ``` …and then run Prettier: ```js const user = { name: "John Doe", age: 30 }; ``` And if you’d like to go multi-line again, add in a newline after `{`: ```js const user = { name: "John Doe", age: 30 }; ``` …and run Prettier: ```js const user = { name: "John Doe", age: 30, }; ``` [object lists]: https://github.com/prettier/prettier/issues/74#issue-199965534 [nested configs]: https://github.com/prettier/prettier/issues/88#issuecomment-275448346 [stylesheets]: https://github.com/prettier/prettier/issues/74#issuecomment-275262094 [keyed methods]: https://github.com/prettier/prettier/pull/495#issuecomment-275745434 :::note[A note on formatting reversibility] The semi-manual formatting for object literals is in fact a workaround, not a feature. It was implemented only because at the time a good heuristic wasn’t found and an urgent fix was needed. However, as a general strategy, Prettier avoids _non-reversible_ formatting like that, so the team is still looking for heuristics that would allow either to remove this behavior completely or at least to reduce the number of situations where it’s applied. What does **reversible** mean? Once an object literal becomes multiline, Prettier won’t collapse it back. If in Prettier-formatted code, we add a property to an object literal, run Prettier, then change our mind, remove the added property, and then run Prettier again, we might end up with a formatting not identical to the initial one. This useless change might even get included in a commit, which is exactly the kind of situation Prettier was created to prevent. ::: ### 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. ```ts @Component({ selector: "hero-button", template: ``, }) class HeroButtonComponent { // These decorators were written inline and fit on the line so they stay // inline. @Output() change = new EventEmitter(); @Input() label: string; // These were written multiline, so they stay multiline. @readonly @nonenumerable NODE_TYPE: 2; } ``` There’s one exception: classes. We don’t think it ever makes sense to inline the decorators for them, so they are always moved to their own line. ```ts // Before running Prettier: @observer class OrderLine { @observable price: number = 0; } ``` ```ts // After running Prettier: @observer class OrderLine { @observable price: number = 0; } ``` Note: Prettier 1.14.x and older tried to automatically move your decorators, so if you've run an older Prettier version on your code you might need to manually join up some decorators here and there to avoid inconsistencies: ```ts @observer class OrderLine { @observable price: number = 0; @observable amount: number = 0; } ``` One final thing: TC39 has [not yet decided if decorators come before or after `export`](https://github.com/tc39/proposal-decorators/issues/69). In the meantime, Prettier supports both: ```js @decorator export class Foo {} export @decorator class Foo {} ``` ### Template literals Template literals can contain interpolations. Deciding whether it's appropriate to insert a linebreak within an interpolation unfortunately depends on the semantic content of the template - for example, introducing a linebreak in the middle of a natural-language sentence is usually undesirable. Since Prettier doesn't have enough information to make this decision itself, it uses a heuristic similar to that used for objects: it will only split an interpolation expression across multiple lines if there was already a linebreak within that interpolation. This means that a literal like the following will not be broken onto multiple lines, even if it exceeds the print width: ```js `this is a long message which contains an interpolation: ${format(data)} <- like this`; ``` If you want Prettier to split up an interpolation, you'll need to ensure there's a linebreak somewhere within the `${...}`. Otherwise it will keep everything on a single line, no matter how long it is. The team would prefer not to depend on the original formatting in this way, but it's the best heuristic we have at the moment. ### Semicolons This is about using the [noSemi](options.md#semicolons) option. Consider this piece of code: ```js if (shouldAddLines) { [-1, 1].forEach(delta => addLine(delta * 20)) } ``` While the above code works just fine without semicolons, Prettier actually turns it into: ```js if (shouldAddLines) { ;[-1, 1].forEach(delta => addLine(delta * 20)) } ``` This is to help you avoid mistakes. Imagine Prettier _not_ inserting that semicolon and adding this line: ```diff if (shouldAddLines) { + console.log('Do we even get here??') [-1, 1].forEach(delta => addLine(delta * 20)) } ``` Oops! The above actually means: ```js if (shouldAddLines) { console.log('Do we even get here??')[-1, 1].forEach(delta => addLine(delta * 20)) } ``` With a semicolon in front of that `[` such issues never happen. It makes the line independent of other lines so you can move and add lines without having to think about ASI rules. This practice is also common in [standard] which uses a semicolon-free style. Note that if your program currently has a semicolon-related bug in it, Prettier _will not_ auto-fix the bug for you. Remember, Prettier only reformats code, it does not change the behavior of the code. Take this buggy piece of code as an example, where the developer forgot to place a semicolon before the `(`: ```js console.log('Running a background task') (async () => { await doBackgroundWork() })() ``` If you feed this into Prettier, it will not alter the behavior of this code, instead, it will reformat it in a way that shows how this code will actually behave when ran. ```js console.log("Running a background task")(async () => { await doBackgroundWork(); })(); ``` [standard]: https://standardjs.com/rules.html#semicolons ### Print width 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 :) Apart from that, there are a few cases where Prettier intentionally exceeds the print width. #### Imports Prettier can break long `import` statements across several lines: ```js import { CollectionDashboard, DashboardPlaceholder, } from "../components/collections/collection-dashboard/main"; ``` The following example doesn’t fit within the print width, but Prettier prints it in a single line anyway: ```js import { CollectionDashboard } from "../components/collections/collection-dashboard/main"; ``` This might be unexpected by some, but we do it this way since it was a common request to keep `import`s with single elements in a single line. The same applies for `require` calls. #### Testing functions Another common request was to keep lengthy test descriptions in one line, even if it gets too long. In such cases, wrapping the arguments to new lines doesn’t help much. ```js describe("NodeRegistry", () => { it("makes no request if there are no nodes to prefetch, even if the cache is stale", async () => { // The above line exceeds the print width but stayed on one line anyway. }); }); ``` Prettier has special cases for common testing framework functions such as `describe`, `it` and `test`. ### JSX Prettier prints things a little differently compared to other JS when JSX is involved: ```jsx function greet(user) { return user ? `Welcome back, ${user.name}!` : "Greetings, traveler! Sign up today!"; } function Greet({ user }) { return (
{user ? (

Welcome back, {user.name}!

) : (

Greetings, traveler! Sign up today!

)}
); } ``` There are two reasons. First off, lots of people already wrapped their JSX in parentheses, especially in `return` statements. Prettier follows this common style. Secondly, [the alternate formatting makes it easier to edit the JSX](https://github.com/prettier/prettier/issues/2208). It is easy to leave a semicolon behind. As opposed to normal JS, a leftover semicolon in JSX can end up as plain text showing on your page. ```jsx

Greetings, traveler! Sign up today!

; {/* <-- Oops! */}
``` ### Comments 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. Generally, you get the best results when placing comments **on their own lines,** instead of at the end of lines. Prefer `// eslint-disable-next-line` over `// eslint-disable-line`. Note that “magic comments” such as `eslint-disable-next-line` and `$FlowFixMe` might sometimes need to be manually moved due to Prettier breaking an expression into multiple lines. Imagine this piece of code: ```js // eslint-disable-next-line no-eval const result = safeToEval ? eval(input) : fallback(input); ``` Then you need to add another condition: ```js // eslint-disable-next-line no-eval const result = safeToEval && settings.allowNativeEval ? eval(input) : fallback(input); ``` Prettier will turn the above into: ```js // eslint-disable-next-line no-eval const result = safeToEval && settings.allowNativeEval ? eval(input) : fallback(input); ``` Which means that the `eslint-disable-next-line` comment is no longer effective. In this case you need to move the comment: ```js const result = // eslint-disable-next-line no-eval safeToEval && settings.allowNativeEval ? eval(input) : fallback(input); ``` 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. ## Disclaimer about machine-generated files Some files, like `package.json` or `composer.lock`, are machine-generated and regularly updated by the package manager. If Prettier were to use the same JSON formatting rules as with other files, it would regularly conflict with these other tools. To avoid this inconvenience, Prettier will use a formatter based on `JSON.stringify` on such files instead. You may notice these differences, such as the removal of vertical whitespace, but this is an intended behavior. ## What Prettier is _not_ concerned about Prettier only _prints_ code. It does not transform it. This is to limit the scope of Prettier. Let’s focus on the printing and do it really well! Here are a few examples of things that are out of scope for Prettier: - Turning single- or double-quoted strings into template literals or vice versa. - Using `+` to break long string literals into parts that fit the print width. - Adding/removing `{}` and `return` where they are optional. - Turning `?:` into `if`-`else` statements. - Sorting/moving imports, object keys, class members, JSX keys, CSS properties or anything else. Apart from being a _transform_ rather than just printing (as mentioned above), sorting is potentially unsafe because of side effects (for imports, as an example) and makes it difficult to verify the most important [correctness](#correctness) goal. --- ### Related Projects --- id: related-projects title: Related Projects --- ## ESLint Integrations - [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-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` ## Forks - [prettierx](https://github.com/brodybits/prettierx) less opinionated fork of Prettier ## Misc - [parallel-prettier](https://github.com/microsoft/parallel-prettier) is an alternative CLI that formats files in parallel to speed up large projects - [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 - [spotless](https://github.com/diffplug/spotless) lets you run prettier from [gradle](https://github.com/diffplug/spotless/tree/main/plugin-gradle#prettier) or [maven](https://github.com/diffplug/spotless/tree/main/plugin-maven#prettier). - [csharpier](https://github.com/belav/csharpier) is a port of Prettier for C# - [reviewdog-action-prettier](https://github.com/EPMatt/reviewdog-action-prettier) runs Prettier in GitHub Actions CI/CD workflows --- ### Sharing configurations --- id: sharing-configurations title: Sharing configurations --- import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; In case you have many different projects, it can be helpful to have a **shared configuration** which can be used in all of them, instead of copy-pasting the same config for every project. This page explains how to create, publish and consume a shareable config. ## Creating a Shareable Config Sharable configs are just [npm packages](https://docs.npmjs.com/about-packages-and-modules#about-packages) that export a single [prettier config file](./configuration.md). Before we start, make sure you have: - An account for [npmjs.com](https://www.npmjs.com/) to publish the package - Basic understating about [how to create a Node.js module](https://docs.npmjs.com/creating-node-js-modules) First, create a new package. We recommend creating a [scoped package](https://docs.npmjs.com/cli/v10/using-npm/scope) with the name `@username/prettier-config`. A minimal package should have at least two files. A `package.json` for the package configuration and an `index.js` which holds the shared prettier configuration object: ```text prettier-config/ ├── index.js └── package.json ``` Example `package.json`: ```json { "name": "@username/prettier-config", "version": "1.0.0", "description": "My personal Prettier config", "type": "module", "exports": "./index.js", "license": "MIT", "publishConfig": { "access": "public" }, "peerDependencies": { "prettier": ">=3.0.0" } } ``` `index.js` is where you put the shared configuration. This file just exports a [regular prettier configuration](./configuration.md) with the same syntax and same options: ```js const config = { trailingComma: "es5", tabWidth: 4, singleQuote: true, }; export default config; ``` An example shared configuration repository is available [here](https://github.com/azz/prettier-config). ## Publishing a Shareable Config Once you are ready, you can [publish your package to npm](https://docs.npmjs.com/creating-and-publishing-scoped-public-packages#publishing-scoped-public-packages): ```bash npm publish ``` ## Using a Shareable Config You first need to install your published configuration, for example: ```bash npm install --save-dev @username/prettier-config ``` ```bash yarn add --dev @username/prettier-config ``` ```bash pnpm add --save-dev @username/prettier-config ``` ```bash bun add --dev @username/prettier-config ``` Then, you can reference it in your `package.json`: ```json { "name": "my-cool-library", "version": "1.0.0", "prettier": "@username/prettier-config" } ``` 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 "@company/prettier-config" ``` ### Extending a Sharable Config To _extend_ the configuration to overwrite some properties from the shared configuration, import the file in a `.prettierrc.mjs` file and export the modifications, e.g: ```js import usernamePrettierConfig from "@username/prettier-config"; /** * @type {import("prettier").Config} */ const config = { ...usernamePrettierConfig, semi: false, }; export default config; ``` ## Other examples ### Using Type Annotation in the Shared Config You can get type safety and autocomplete support in your shared configuration by using a `jsdoc` type annotation: ```js /** * @type {import("prettier").Config} */ const config = { trailingComma: "es5", tabWidth: 4, semi: false, singleQuote: true, }; export default config; ``` In order to make this work, you have to [install `prettier`](./install.md) for the project. After that, your `package.json` file should look like this: ```diff { "name": "@username/prettier-config", "version": "1.0.0", "description": "My personal Prettier config", "type": "module", "exports": "./index.js", "license": "MIT", "publishConfig": { "access": "public" }, "peerDependencies": { "prettier": ">=3.0.0" }, + "devDependencies": { + "prettier": "^3.3.3" + } } ``` ### Include Plugins in Shareable Configurations In case you want to use [plugins](./plugins.md) in your shared configuration, you need to declare those plugins in the config file's `plugin` array and as `dependencies` in `package.json`: ```js // index.js const config = { singleQuote: true, plugins: ["prettier-plugin-xml"], }; export default config; ``` ```diff // package.json { "name": "@username/prettier-config", "version": "1.0.0", "description": "My personal Prettier config", "type": "module", "exports": "./index.js", "license": "MIT", "publishConfig": { "access": "public" }, + "dependencies": { + "prettier-plugin-xml": "3.4.1" + }, "peerDependencies": { "prettier": ">=3.0.0" } } ``` An example repository can be found [here](https://github.com/kachkaev/routine-npm-packages/tree/bc3e658f88c0b41beb118c7a1b9b91ec647f8478/packages/prettier-config) **Note:** You can use [`peerDependencies`](https://docs.npmjs.com/cli/v10/configuring-npm/package-json#peerdependencies) instead of [`dependencies`](https://docs.npmjs.com/cli/v10/configuring-npm/package-json#dependencies). To learn about their differences, you can read [this blog post from Domenic Denicola about peer dependencies](https://nodejs.org/en/blog/npm/peer-dependencies) --- ### Technical Details --- id: technical-details title: 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. 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, `["(", 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. The [Playground](https://prettier.io/playground) has a special mode for exploring how Prettier’s intermediate representation is printed. To get there, open the sidebar (the "Show options" button) and set the `parser` option to the special value `doc-explorer`. More (rough) details can be found in [commands.md](https://github.com/prettier/prettier/blob/main/commands.md). --- ### Vim Setup --- id: vim title: Vim Setup --- 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/dense-analysis/ale) which are generalized lint/format engines with support for Prettier. ## [vim-prettier](https://github.com/prettier/vim-prettier) See the [vim-prettier](https://github.com/prettier/vim-prettier) readme for installation and usage instructions. ## [Neoformat](https://github.com/sbdchd/neoformat) The best way to install Neoformat is with your favorite plugin manager for Vim, such as [vim-plug](https://github.com/junegunn/vim-plug): ```vim Plug 'sbdchd/neoformat' ``` In order for Neoformat to use a project-local version of Prettier (i.e. to use `node_modules/.bin/prettier` instead of looking for `prettier` on `$PATH`), you must set the `neoformat_try_node_exe` option: ```vim let g:neoformat_try_node_exe = 1 ``` Run `:Neoformat` or `:Neoformat prettier` in a supported file to run Prettier. To have Neoformat run Prettier on save: ```vim autocmd BufWritePre *.js Neoformat ``` You can also make Vim format your code more frequently, by setting an `autocmd` for other events. Here are a couple of useful ones: - `TextChanged`: after a change was made to the text in Normal mode - `InsertLeave`: when leaving Insert mode For example, you can format on both of the above events together with `BufWritePre` like this: ```vim 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`: ```vim autocmd FileType javascript setlocal formatprg=prettier\ --single-quote\ --trailing-comma\ es5 " Use formatprg when available let g:neoformat_try_formatprg = 1 ``` Each space in Prettier options should be escaped with `\`. ## [ALE](https://github.com/dense-analysis/ale) ALE requires either Vim 8 or Neovim as ALE makes use of the asynchronous abilities that both Vim 8 and Neovim provide. The best way to install ALE is with your favorite plugin manager for Vim, such as [vim-plug](https://github.com/junegunn/vim-plug): ```vim Plug 'dense-analysis/ale' ``` You can find further instructions on the [ALE repository](https://github.com/dense-analysis/ale#3-installation). ALE will try to use Prettier installed locally before looking for a global installation. Enable the Prettier fixer for the languages you use: ```vim let g:ale_fixers = { \ 'javascript': ['prettier'], \ 'css': ['prettier'], \} ``` ALE supports both _linters_ and _fixers_. If you don’t specify which _linters_ to run, **all available tools for all supported languages will be run,** and you might get a correctly formatted file with a bunch of lint errors. To disable this behavior you can tell ALE to run only linters you've explicitly configured (more info in the [FAQ](https://github.com/dense-analysis/ale/blob/ed8104b6ab10f63c78e49b60d2468ae2656250e9/README.md#faq-disable-linters)): ```vim let g:ale_linters_explicit = 1 ``` You can then run `:ALEFix` in a JavaScript or CSS file to run Prettier. To have ALE run Prettier on save: ```vim 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`: ```vim let g:ale_javascript_prettier_options = '--single-quote --trailing-comma all' ``` ## [coc-prettier](https://github.com/neoclide/coc-prettier) Prettier extension for [coc.nvim](https://github.com/neoclide/coc.nvim) which requires neovim or vim8.1. Install coc.nvim with your favorite plugin manager, such as [vim-plug](https://github.com/junegunn/vim-plug): ```vim Plug 'neoclide/coc.nvim', {'branch': 'release'} ``` And install coc-prettier by command: ```vim CocInstall coc-prettier ``` Setup `Prettier` command in your `init.vim` or `.vimrc` ```vim command! -nargs=0 Prettier :call CocAction('runCommand', 'prettier.formatFile') ``` Update your `coc-settings.json` for languages that you want format on save. ```json { "coc.preferences.formatOnSaveFiletypes": ["css", "markdown"] } ``` [coc-prettier](https://github.com/neoclide/coc-prettier) have same configurations of [prettier-vscode](https://github.com/prettier/prettier-vscode), open `coc-settings.json` by `:CocConfig` to get autocompletion support. ## Running manually If you want something really bare-bones, you can create a custom key binding. In this example, `gp` (mnemonic: "get pretty") is used to run prettier (with options) in the currently active buffer: ```vim 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. Another disadvantage of this approach is that the cursor position won’t be preserved. --- ### Watching For Changes --- id: watching-files title: Watching For Changes --- 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 "**/*" -- npx prettier --write --ignore-unknown {{changed}} ``` Or add the following to your `package.json`: ```json { "scripts": { "prettier-watch": "onchange \"**/*\" -- prettier --write --ignore-unknown {{changed}}" } } ``` --- ### WebStorm Setup --- id: webstorm title: WebStorm Setup --- ## JetBrains IDEs (WebStorm, IntelliJ IDEA, PyCharm, etc.) WebStorm comes with built-in support for Prettier. If you’re using other JetBrains IDE like IntelliJ IDEA, PhpStorm, or PyCharm, make sure you have this [plugin](https://plugins.jetbrains.com/plugin/10456-prettier) installed and enabled in _Preferences / Settings | Plugins_. First, you need to install and configure Prettier. You can find instructions on how to do it [here](https://www.jetbrains.com/help/webstorm/prettier.html#ws_prettier_install). Once it’s done, you can do a few things in your IDE. You can 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. You can also configure WebStorm to run Prettier on save (_Cmd+S/Ctrl+S_) or use it as the default formatter (_Opt+Cmd+L/Ctrl+Alt+L_). For this, open _Preferences / Settings | Languages & Frameworks | JavaScript | Prettier_ and tick the corresponding checkbox: **On save** and/or **On ‘Reformat Code’** action. ![Example](/images/webstorm/prettier-settings.png) By default, WebStorm will apply formatting to all _.js, .ts, .jsx_, and _.tsx_ files that you’ve edited in your project. To apply the formatting to other file types, or to limit formatting to files located only in specific directories, you can customize the default configuration by using [glob patterns](https://github.com/isaacs/node-glob). For more information, see [WebStorm online help](https://www.jetbrains.com/help/webstorm/prettier.html). --- ### Why Prettier? --- id: why-prettier title: Why Prettier? --- ## Building and enforcing a style guide By far the biggest reason for adopting Prettier is to stop all the on-going debates over styles. [It is generally accepted that having a common style guide is valuable for a project and team](https://www.smashingmagazine.com/2012/10/why-coding-style-matters/) but getting there is a very painful and unrewarding process. People get very emotional around particular ways of writing code and nobody likes spending time writing and receiving nits. So why choose the “Prettier style guide” over any other random style guide? Because Prettier is the only “style guide” that is fully automatic. Even if Prettier does not format all code 100% the way you’d like, it’s worth the “sacrifice” given the unique benefits of Prettier, don’t you think? - “We want to free mental threads and end discussions around style. While sometimes fruitful, these discussions are for the most part wasteful.” - “Literally had an engineer go through a huge effort of cleaning up all of our code because we were debating ternary style for the longest time and were inconsistent about it. It was dumb, but it was a weird on-going “great debate” that wasted lots of little back and forth bits. It’s far easier for us all to agree now: just run Prettier, and go with that style.” - “Getting tired telling people how to style their product code.” - “Our top reason was to stop wasting our time debating style nits.” - “Having a githook set up has reduced the amount of style issues in PRs that result in broken builds due to ESLint rules or things I have to nit-pick or clean up later.” - “I don’t want anybody to nitpick any other person ever again.” - “It reminds me of how Steve Jobs used to wear the same clothes every day because he has a million decisions to make and he didn’t want to be bothered to make trivial ones like picking out clothes. I think Prettier is like that.” ## Helping Newcomers Prettier is usually introduced by people with experience in the current codebase and JavaScript but the people that disproportionally benefit from it are newcomers to the codebase. One may think that it’s only useful for people with very limited programming experience, but we've seen it quicken the ramp up time from experienced engineers joining the company, as they likely used a different coding style before, and developers coming from a different programming language. - “My motivations for using Prettier are: appearing that I know how to write JavaScript well.” - “I always put spaces in the wrong place, now I don’t have to worry about it anymore.” - “When you're a beginner you're making a lot of mistakes caused by the syntax. Thanks to Prettier, you can reduce these mistakes and save a lot of time to focus on what really matters.” - “As a teacher, I will also tell to my students to install Prettier to help them to learn the JS syntax and have readable files.” ## Writing code What usually happens once people are using Prettier is that they realize that they actually spend a lot of time and mental energy formatting their code. With Prettier editor integration, you can just press that magic key binding and poof, the code is formatted. This is an eye opening experience if anything else. - “I want to write code. Not spend cycles on formatting.” - “It removed 5% that sucks in our daily life - aka formatting” - “We're in 2017 and it’s still painful to break a call into multiple lines when you happen to add an argument that makes it go over the 80 columns limit :(“ ## Easy to adopt We've worked very hard to use the least controversial coding styles, went through many rounds of fixing all the edge cases and polished the getting started experience. When you're ready to push Prettier into your codebase, not only should it be painless for you to do it technically but the newly formatted codebase should not generate major controversy and be accepted painlessly by your co-workers. - “It’s low overhead. We were able to throw Prettier at very different kinds of repos without much work.” - “It’s been mostly bug free. Had there been major styling issues during the course of implementation we would have been wary about throwing this at our JS codebase. I’m happy to say that’s not the case.” - “Everyone runs it as part of their pre commit scripts, a couple of us use the editor on save extensions as well.” - “It’s fast, against one of our larger JS codebases we were able to run Prettier in under 13 seconds.” - “The biggest benefit for Prettier for us was being able to format the entire code base at once.” ## Clean up an existing codebase Since coming up with a coding style and enforcing it is a big undertaking, it often slips through the cracks and you are left working on inconsistent codebases. Running Prettier in this case is a quick win, the codebase is now uniform and easier to read without spending hardly any time. - “Take a look at the code :) I just need to restore sanity.” - “We inherited a ~2000 module ES6 code base, developed by 20 different developers over 18 months, in a global team. Felt like such a win without much research.” ## Ride the hype train Purely technical aspects of the projects aren’t the only thing people look into when choosing to adopt Prettier. Who built and uses it and how quickly it spreads through the community has a non-trivial impact. - “The amazing thing, for me, is: 1) Announced 2 months ago. 2) Already adopted by, it seems, every major JS project. 3) 7000 stars, 100,000 npm downloads/mo” - “Was built by the same people as React & React Native.” - “I like to be part of the hot new things.” - “Because soon enough people are gonna ask for it.”