Prettier
Supported languages
- JavaScript
- JSX
- Angular
- Vue
- Flow
- TypeScript
- CSS, Less, SCSS
- HTML
- Ember/Handlebars
- JSON
- GraphQL
- Markdown (GFM + MDX v1)
- YAML
Setup
pnpm add --save-dev prettier
.prettierignore
-.git
,node_modules
are ignored by default.- Prettier uses cosmiconfig, and thus the following config files are supported
prettier
- key inpackage.json
.prettierrc
- json/yaml format.prettierrc.json
,.prettierrc.yml
,.prettierrc.yaml
,.prettierrc.json5
.prettierrc.js
,prettier.config.js
- withexport default
.prettierrc.mjs
,prettier.config.mjs
- withexport default
.prettierrc.cjs
,prettier.config.cjs
- withmodule.exports
.prettierrc.toml
- JSON schema to validate prettier config can be found at https://json.schemastore.org/prettierrc.
pnpm exec prettier . --write
- format all files in directory.-
pnpm exec prettier . --check
- check if files are formatted. Useful in CI pipelines.Returns the following exit codes
0
- everything formatted properly1
- something wasn't formatted properly2
- something wrong with prettier
Performance
For performance, provide the path to .prettierrc
, .prettierignore
file in the CLI. This avoids prettier to do the lookup.
pnpm exec prettier . --write --config path/to/.prettierrc --ignore-path .prettierignore .gitignore
Cache
Prettier stores the cache in ./node_modules/.cache/prettier/.prettier-cache
(controlled by --cache-location
). Files are formatted only when one of the following is changed
- Prettier version
- Options
- Node.js version
--cache-strategy metadata
- like timestamps. This is faster.--cache-strategy content
(default) -git clone
does not track modification times, therefore this is the default.
ESLint
pnpm add --save-dev eslint-config-prettier
- In
.eslintrc
add - Or in
eslint.config.js
add
Usage with linters
Disable linting use line ranges, rather than disabling next line.
For instance, linting for next line can be disabled in ESLint as shown below
But the problem is prettier might move the expression to a new line and the comment would no longer be valid.
Git hooks
In package.json
pre-commit
Add the following in .pre-commit-config.yaml
Ignore code
Use comment prettier-ignore
to exclude the next node in the abstract syntax tree from formatting.
To disable a range of code (only to be used at the top, like autogenerated files or TOC)
Plugins
To create plugins see https://prettier.io/docs/en/plugins.
Options
Add * text=auto eol=lf
to .gitattributes
to ensure lf
is used in the repo.
Override options
Overriding configuration for file extensions
Sharing config
Publish a module that exports a configuration object and reference it in package.json
.
A better approach is to use .prettierrc.js
as that allows to modify the config
Created: November 21, 2023