Home

Awesome

Prettier Miscellaneous

Gitter Build Status CircleCI Status Codecov NPM version styled with prettier

CONFIGURATION WELCOME

This is a fork of prettier/prettier, with a goal of supporting additional options not picked up by official Prettier.

If you want to add an option to Prettier Miscellaneous, please send a PR! 😃

Happyness

Prettier is an opinionated code formatter with support for:

It removes all original styling* and ensures that all outputted code conforms to a consistent style. (See this blog post)

<details> <summary><strong>Table of Contents</strong></summary> </details>

What does Prettier do?

Prettier takes your code and reprints it from scratch by taking the line length into account.

For example, take the following code:

foo(arg1, arg2, arg3, arg4);

It fits in a single line so it's going to stay as is. However, we've all run into this situation:

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:

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* 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.

<a href="#styling-footnote" name="styling-footnote">*</a>Well actually, some original styling is preserved when practical—see empty lines and multi-line objects.

If you want to learn more, these two conference talks are great introductions:

<a href="https://www.youtube.com/watch?v=hkfBvpEfWdA"><img width="298" src="https://cloud.githubusercontent.com/assets/197597/24886367/dda8a6f0-1e08-11e7-865b-22492450f10f.png"></a> <a href="https://www.youtube.com/watch?v=0Q4kUNx85_4"><img width="298" src="https://cloud.githubusercontent.com/assets/197597/24886368/ddacd6f8-1e08-11e7-806a-9febd23cbf47.png"></a>

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 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.

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.

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.

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.

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.

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.

A few of the many projects using Prettier:

<table> <tr> <td><p align="center"><a href="https://facebook.github.io/react/"><img src="website/static/images/react-200x100.png" alt="React" width="200" height="100"><br>React</a></p></td> <td><p align="center"><a href="https://facebook.github.io/jest/"><img src="website/static/images/jest-200x100.png" alt="Jest" width="200" height="100"><br>Jest</a></p></td> <td><p align="center"><a href="https://yarnpkg.com"><img src="website/static/images/yarn-200x100.png" alt="Yarn" width="200" height="100"><br>Yarn</a></p></td> </tr> <tr> <td><p align="center"><a href="https://babeljs.io/"><img src="website/static/images/babel-200x100.png" alt="Babel" width="200" height="100"><br>Babel</a></p></td> <td><p align="center"><a href="https://zeit.co/"><img src="website/static/images/zeit-200x100.png" alt="Zeit" width="200" height="100"><br>Zeit</a></p></td> <td><p align="center"><a href="https://webpack.js.org/api/cli/"><img src="website/static/images/webpack-200x100.png" alt="Webpack-cli" width="200" height="100"><br>Webpack-cli</a></p></td> </tr> </table>

How does it compare to ESLint (or TSLint, stylelint...)?

Linters have two categories of rules:

Formatting rules: eg: max-len, no-mixed-spaces-and-tabs, keyword-spacing, 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, no-extra-bind, no-implicit-globals, 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!

Usage

Install:

yarn add prettier-miscellaneous --dev

You can install it globally if you like:

yarn global add prettier-miscellaneous

We're using yarn but you can use npm if you like:

npm install [--save-dev|--global] prettier-miscellaneous

CLI

Run Prettier through the CLI with this script. Run it without any arguments to see the options.

To format a file in-place, use --write. You may want to consider committing your code before doing that, just in case.

prettier [opts] [filename ...]

In practice, this may look something like:

prettier --single-quote --trailing-comma es5 --write "{app,__{tests,mocks}__}/**/*.js"

Don't forget the quotes around the globs! The quotes make sure that Prettier expands the globs rather than your shell, for cross-platform usage. The glob syntax from the glob module is used.

--with-node-modules

Prettier CLI will ignore files located in node_modules directory. To opt-out from this behavior use --with-node-modules flag.

--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.

prettier --single-quote --list-different "src/**/*.js"

--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. In order to skip this, you may ask prettier to find the config file once, and re-use it later on.

prettier --find-config-path ./my/file.js
./my/.prettierrc

This will provide you with a path to the configuration file, which you can pass to --config:

prettier --config ./my/.prettierrc --write ./my/file.js

You can also use --config if your configuration file lives somewhere where prettier cannot find it, such as a config/ directory.

If you don't have a configuration file, or want to ignore it if it does exist, you can pass --no-config instead.

--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.

ESLint

If you are using ESLint, integrating Prettier to your workflow is straightforward:

Just add Prettier as an ESLint rule using eslint-plugin-prettier.

yarn add --dev prettier eslint-plugin-prettier

// .eslintrc
{
  "plugins": [
    "prettier"
  ],
  "rules": {
    "prettier/prettier": "error"
  }
}

We also recommend that you use eslint-config-prettier to disable all the existing formatting rules. It's a one liner that can be added on-top of any existing ESLint configuration.

$ yarn add --dev eslint-config-prettier

.eslintrc.json:

{
  "extends": [
    "prettier"
  ]
}

Pre-commit Hook

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

Install it along with husky:

yarn add lint-staged husky --dev

and add this config to your package.json:

{
  "scripts": {
    "precommit": "lint-staged"
  },
  "lint-staged": {
    "*.js": [
      "prettier --write",
      "git add"
    ]
  }
}

See https://github.com/okonet/lint-staged#configuration for more details about how you can configure lint-staged.

Option 2. pre-commit

Copy the following config into your .pre-commit-config.yaml file:


    -   repo: https://github.com/prettier/prettier
        sha: ''  # Use the sha or tag you want to point at
        hooks:
        -   id: prettier

Find more info from here.

Option 3. bash script

Alternately you can save this script as .git/hooks/pre-commit and give it execute permission:

#!/bin/sh
jsfiles=$(git diff --cached --name-only --diff-filter=ACM | grep '\.jsx\?$' | tr '\n' ' ')
[ -z "$jsfiles" ] && exit 0

# Prettify all staged .js files
echo "$jsfiles" | xargs ./node_modules/.bin/prettier --write

# Add back the modified/prettified files to staging
echo "$jsfiles" | xargs git add

exit 0

Options

Prettier ships with a handful of customizable format options, usable in both the CLI and API.

OptionDefaultOverride
Print Width - Specify the length of line that the printer will wrap on.<br /><br /><strong>We strongly recommend against using more than 80 columns</strong>. Prettier works by cramming as much content as possible until it reaches the limit, which happens to work well for 80 columns but makes lines that are very crowded. When a bigger column count is used in styleguides, it usually means that code is allowed to go beyond 80 columns, but not to make every single line go there, like prettier would do.80CLI: --print-width <int> <br />API: printWidth: <int>
Tab Width - Specify the number of spaces per indentation-level.2CLI: --tab-width <int> <br />API: tabWidth: <int>
Tabs - Indent lines with tabs instead of spaces.falseCLI: --use-tabs <br />API: useTabs: <bool>
Semicolons - Print semicolons at the ends of statements.<br /><br />Valid options: <ul><li>true - add a semicolon at the end of every statement</li><li>false - only add semicolons at the beginning of lines that may introduce ASI failures</li></ul>trueCLI: --no-semi <br />API: semi: <bool>
Quotes - Use single quotes instead of double quotes.<br /><br />Notes:<ul><li>Quotes in JSX will always be double and ignore this setting, unless --jsx-single-quote is used.</li><li>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'.</li></ul>falseCLI: --single-quote <br />API: singleQuote: <bool>
JSX Single Quote - Use single quotes instead of double quotes for JSX attributes.falseCLI: --jsx-single-quote <br />API: jsxSingleQuote: <bool>
Trailing Commas - Print trailing commas wherever possible.<br /><br />Valid options: <ul><li>"none" - no trailing commas </li><li>"es5" - trailing commas where valid in ES5 (objects, arrays, etc.)</li><li>"all" - trailing commas wherever possible (function arguments). This requires node 8 or a transform.</li></ul>"none"CLI: <code>--trailing-comma <none|es5|all></code> <br />API: <code>trailingComma: "<none|es5|all>"</code>
Trailing Commas (extended) - You can also customize each place to use trailing commas:<br /><br />Valid options: <br /> - "array" <br/> - "object" <br /> - "import" <br /> - "export" <br /> - "arguments""none"You can use a comma separated string list, or an object in the API.<br /><br />CLI: <code>--trailing-comma "array,object,import,export,arguments"</code> <br />API: <code>trailingComma: { array: true, object: true, import: true, export: true, arguments: false }</code>
Bracket Spacing - Print spaces between brackets in array literals.<br /><br />Valid options: <br /> - true - Example: [ foo: bar ] <br /> - false - Example: [foo: bar]trueCLI: --no-bracket-spacing <br/>API: bracketSpacing: <bool>
Braces Spacing - Print spaces between braces in object literals.<br /><br />Valid options: <ul><li>true - Example: { foo: bar }</li><li>false - Example: {foo: bar}</li>trueCLI: --no-braces-spacing <br />API: bracesSpacing: <bool>
JSX Brackets on Same Line - Put the > of a multi-line JSX element at the end of the last line instead of being alone on the next linefalseCLI: --jsx-bracket-same-line <br />API: jsxBracketSameLine: <bool>
Align Object Properties - Align colons in multiline object literals. Does nothing if object has computed property names.falseCLI: --align-object-properties <br/>API: alignObjectProperties: <bool>
No Space in Empty Function - Omit space before empty anonymous function body.<br /><br />Valid options: <br /> - true <br /> - falsefalseCLI: --no-space-empty-fn <br/>API: noSpaceEmptyFn: <bool>
Space before Function Paren - Put a space before function parenthesis.<br /><br />Valid options: <br /> - true <br /> - falsefalseCLI: --space-before-function-paren <br/>API: spaceBeforeFunctionParen: <bool>
Cursor Offset - Specify where the cursor is. This option only works with prettier.formatWithCursor, and cannot be used with rangeStart and rangeEnd.-1CLI: --cursor-offset <int> <br />API: cursorOffset: <int>
Range Start - Format code starting at a given character offset. The range will extend backwards to the start of the first line containing the selected statement. This option cannot be used with cursorOffset.0CLI: --range-start <int> <br />API: rangeStart: <int>
Range End - Format code ending at a given character offset (exclusive). The range will extend forwards to the end of the selected statement. This option cannot be used with cursorOffset.InfinityCLI: --range-end <int> <br />API: rangeEnd: <int>
Parser - Specify which parser to use. Both the babylon and flow parsers support the same set of JavaScript features (including Flow). Prettier automatically infers the parser from the input file path, so you shouldn't have to change this setting. <br />Built-in parsers: <ul><li>babylon</li><li>flow</li><li>typescript</li><li>postcss</li><li>json</li></ul>Custom parsers are also supported.babylonCLI: <br />--parser <string> <br />--parser ./path/to/my-parser <br />API: <br />parser: "<string>" <br />parser: require("./my-parser")
Filepath - Specify the input filepath this will be used to do parser inference.<br /><br /> Example: <br />cat foo | prettier --stdin-filepath foo.css<br /> will default to use postcss parserCLI: --stdin-filepath <br />API: filepath: "<string>"

API

const prettier = require("prettier-miscellaneous");

prettier.format(source [, options])

format is used to format text using Prettier. Options may be provided to override the defaults.

prettier.format("foo ( );", { semi: false });
// -> "foo()"

prettier.check(source [, options])

check checks to see if the file has been formatted with Prettier given those options and returns a Boolean. This is similar to the --list-different parameter in the CLI and is useful for running Prettier in CI scenarios.

prettier.formatWithCursor(source [, options])

formatWithCursor both formats the code, and translates a cursor position from unformatted code to formatted code. This is useful for editor integrations, to prevent the cursor from moving when code is formatted.

The cursorOffset option should be provided, to specify where the cursor is. This option cannot be used with rangeStart and rangeEnd.

prettier.formatWithCursor(" 1", { cursorOffset: 2 });
// -> { formatted: '1;\n', cursorOffset: 1 }

prettier.resolveConfig([filePath] [, options])

resolveConfig can be used to resolve configuration for a given source file. The function optionally accepts an input file path as an argument, which defaults to the current working directory. A promise is returned which will resolve to:

The promise will be rejected if there was an error parsing the configuration file.

If options.withCache is false, all caching will be bypassed.

const text = fs.readFileSync(filePath, "utf8");
prettier.resolveConfig(filePath).then(options => {
  const formatted = prettier.format(text, options);
})

prettier.clearConfigCache()

As you repeatedly call resolveConfig, the file system structure will be cached for performance. This function will clear the cache. Generally this is only needed for editor integrations that know that the file system has changed since the last format took place.

Custom Parser API

If you need to make modifications to the AST (such as codemods), or you want to provide an alternate parser, you can do so by setting the parser option to a function. The function signature of the parser function is:

(text: string, parsers: object, options: object) => AST;

Prettier's built-in parsers are exposed as properties on the parsers argument.

prettier.format("lodash ( )", {
  parser(text, { babylon }) {
    const ast = babylon(text);
    ast.program.body[0].expression.callee.name = "_";
    return ast;
  }
});
// -> "_();\n"

The --parser CLI option may be a path to a node.js module exporting a parse function.

Excluding code from formatting

A JavaScript comment of // prettier-ignore will exclude the next node in the abstract syntax tree from formatting.

For example:

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:

matrix(1, 0, 0, 0, 1, 0, 0, 0, 1);

// prettier-ignore
matrix(
  1, 0, 0,
  0, 1, 0,
  0, 0, 1
)

Options

Prettier ships with a handful of customizable format options, usable in both the CLI and API.

Print Width

Specify the line length that the printer will wrap on.

For readability we recommend against using more than 80 characters:

In code styleguides, maximum line length rules are often set to 100 or 120. However, when humans write code, they don't strive to reach the maximum number of columns on every line. Developers often use whitespace to break up long lines for readability. In practice, the average line length often ends up well below the maximum.

Prettier, on the other hand, strives to fit the most code into every line. With the print width set to 120, prettier may produce overly compact, or otherwise undesirable code.

DefaultCLI OverrideAPI Override
80--print-width <int>printWidth: <int>

Tab Width

Specify the number of spaces per indentation-level.

DefaultCLI OverrideAPI Override
2--tab-width <int>tabWidth: <int>

Tabs

Indent lines with tabs instead of spaces

DefaultCLI OverrideAPI Override
false--use-tabsuseTabs: <bool>

Semicolons

Print semicolons at the ends of statements.

Valid options:

DefaultCLI OverrideAPI Override
true--no-semisemi: <bool>

Quotes

Use single quotes instead of double quotes.

Notes:

DefaultCLI OverrideAPI Override
false--single-quotesingleQuote: <bool>

Trailing Commas

Print trailing commas wherever possible.

Valid options:

DefaultCLI OverrideAPI Override
"none"<code>--trailing-comma <none|es5|all></code><code>trailingComma: "<none|es5|all>"</code>

Bracket Spacing

Print spaces between brackets in object literals.

Valid options:

DefaultCLI OverrideAPI Override
true--no-bracket-spacingbracketSpacing: <bool>

JSX Brackets

Put the > of a multi-line JSX element at the end of the last line instead of being alone on the next line.

DefaultCLI OverrideAPI Override
false--jsx-bracket-same-linejsxBracketSameLine: <bool>

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:

These options cannot be used with cursorOffset.

DefaultCLI OverrideAPI Override
0--range-start <int>rangeStart: <int>
Infinity--range-end <int>rangeEnd: <int>

Parser

Specify which parser to use.

Both the babylon and flow parsers support the same set of JavaScript features (including Flow). Prettier automatically infers the parser from the input file path, so you shouldn't have to change this setting.

Built-in parsers:

Custom parsers are also supported. Since v1.5.0

DefaultCLI OverrideAPI Override
babylon--parser <string><br />--parser ./my-parserparser: "<string>"<br />parser: require("./my-parser")

Filepath

Specify the input filepath. This will be used to do parser inference.

For example, the following will use postcss parser:

cat foo | prettier --stdin-filepath foo.css
DefaultCLI OverrideAPI Override
None--stdin-filepath <string>filepath: "<string>"

Configuration File

Prettier uses cosmiconfig for configuration file support. This means you can configure prettier via:

The configuration file will be resolved starting from the location of the file being formatted, and searching up the file tree until a config file is (or isn't) found.

The options to the configuration file are the same the API options.

Basic Configuration

JSON:

// .prettierrc
{
  "printWidth": 100,
  "parser": "flow"
}

YAML:

# .prettierrc
printWidth: 100
parser: flow

Configuration Overrides

Prettier borrows eslint's override format. This allows you to apply configuration to specific files.

JSON:

{
  "semi": false,
  "overrides": [{
    "files": "*.test.js",
    "options": {
      "semi": true
    }
  }]
}

YAML:

semi: false
overrides:
- files: "*.test.js"
  options:
    semi: true

files is required for each override, and may be a string or array of strings. excludeFiles may be optionally provided to exclude files for a given rule, and may also be a string or array of strings.

To get prettier to format its own .prettierrc file, you can do:

{
  "overrides": [{
    "files": ".prettierrc",
    "options": { "parser": "json" }
  }]
}

For more information on how to use the CLI to locate a file, see the CLI section.

Configuration Schema

If you'd like a JSON schema to validate your configuration, one is available here: http://json.schemastore.org/prettierrc.

Editor Integration

Atom

Atom users can simply install the prettier-atom-with-tabs package and use Ctrl+Alt+F to format a file (or format on save if enabled).

Emacs

Emacs users should see this repository for on-demand formatting.

Vim

Vim users can simply install either sbdchd/neoformat, w0rp/ale, or mitermayer/vim-prettier, for more details see this directory.

Visual Studio Code

Can be installed using the extension sidebar. Search for Prettier - JavaScript formatter.

Can also be installed using ext install prettier-vscode-with-tabs

Check its repository for configuration and shortcuts

Visual Studio

Install the JavaScript Prettier extension.

Sublime Text

Sublime Text support is available through Package Control and the JsPrettier plug-in.

JetBrains WebStorm, PHPStorm, PyCharm...

See the WebStorm guide.

Language Support

Prettier attempts to support all JavaScript language features, including non-standardized ones. By default it uses the Babylon parser with all language features enabled, but you can also use the Flow parser with the parser API or --parser CLI option.

All of JSX and Flow syntax is supported. In fact, the test suite in tests is the entire Flow test suite and they all pass.

Prettier also supports TypeScript, CSS, LESS, SCSS, JSON, and GraphQL.

The minimum version of TypeScript supported is 2.1.3 as it introduces the ability to have leading | for type definitions which prettier outputs.

Related Projects

Technical Details

This printer is a fork of recast's printer with its algorithm replaced by the one described by Wadler in "A prettier printer". There still may be leftover code from recast that needs to be cleaned up.

The basic idea is that the printer takes an AST and returns an intermediate representation of the output, and the printer uses that to generate a string. The advantage is that the printer can "measure" the IR and see if the output is going to fit on a line, and break if not.

This means that most of the logic of printing an AST involves generating an abstract representation of the output involving certain commands. For example, concat(["(", line, arg, line ")"]) would represent a concatenation of opening parens, an argument, and closing parens. But if that doesn't fit on one line, the printer can break where line is specified.

More (rough) details can be found in commands.md.

Badge

Show the world you're using Prettierstyled with prettier

[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier)

Contributing

See CONTRIBUTING.md.