Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
[![Gitter](https://badges.gitter.im/gitterHQ/gitter.svg)](https://gitter.im/jlongster/prettier) [![Build Status](https://travis-ci.org/jlongster/prettier.svg?branch=master)](https://travis-ci.org/jlongster/prettier) [![NPM version](https://img.shields.io/
Prettier is an opinionated code formatter that supports many languages and integrates with most editors. It removes all original styling and ensures that all outputted code conforms to a consistent style.
Code Formatting
Formats all .js files in the src directory and its subdirectories. When run, this command will process each JavaScript file and reformat it according to Prettier's rules.
prettier --write 'src/**/*.js'
Configuration Overrides
Allows customization of Prettier's default formatting rules. For example, this JSON configuration disables semicolons at the end of statements and enforces single quotes.
{
'semi': false,
'singleQuote': true
}
Ignoring Code
You can prevent a section of code from being formatted by Prettier by adding a special comment, `// prettier-ignore`, before it.
// prettier-ignore
let untouched = 'This code will not be formatted by Prettier.';
Integration with Editors
Prettier can be integrated into many code editors to automatically format files on save or during editing, enhancing the developer's workflow.
N/A
Support for Multiple Languages
Prettier supports a wide range of languages and frameworks, including but not limited to JavaScript, TypeScript, CSS, HTML, and Markdown, making it a versatile tool for many developers.
N/A
ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code, with the ability to fix many issues automatically. While it can also format code, its primary focus is on code quality and adherence to coding standards, unlike Prettier which is solely focused on code formatting.
Stylelint is a modern linter that helps you avoid errors and enforce conventions in your stylesheets. It is to CSS what ESLint is to JavaScript, and while it can fix code style issues, it is more focused on maintaining code quality rather than just formatting.
Beautify, available as 'js-beautify' for npm, is a code beautifier that can format HTML, CSS, and JavaScript. It is less opinionated than Prettier and offers more configuration options, but it might not enforce as consistent a style as Prettier does.
Standard is a JavaScript style guide, linter, and formatter that enforces a strict coding standard. Unlike Prettier, Standard also includes rules that aim to prevent bugs and improve code clarity.
Prettier is an opinionated JavaScript formatter inspired by refmt with advanced support for language features from ES2017, JSX, and Flow. It removes all original styling and ensures that all outputted JavaScript conforms to a consistent style. (See this blog post)
Warning: This is a beta, and the format may change over time. If you aren't OK with the format changing, wait for a more stable version.
This goes way beyond eslint and other projects built on it. Unlike eslint, there aren't a million configuration options and rules. But more importantly: everything is fixable. This works because prettier never "checks" anything; it takes JavaScript as input and outputs the formatted JavaScript as output.
In technical terms: prettier parses your JavaScript into an AST and pretty-prints the AST, completely ignoring any of the original formatting. Say hello to completely consistent syntax!
There's an extremely important piece missing from existing styling tools: the maximum line length. Sure, you can tell eslint to warn you when you have a line that's too long, but that's an after-thought (eslint never knows how to fix it). The maximum line length is a critical piece the formatter needs for laying out and wrapping code.
For example, take the following code:
foo(arg1, arg2, arg3);
That looks like the right way to format it. 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. What you would probably do is this instead:
foo(
reallyLongArg(),
omgSoManyParameters(),
IShouldRefactorThis(),
isThereSeriouslyAnotherOne()
);
This clearly shows that the maximum line length has a direct impact on the style of code we desire. The fact that current style tools ignore this means they can't really help with the situations that are actually the most troublesome. Individuals on teams will all format these differently according to their own rules and we lose the consistency we sought after.
Even if we disregard line widths, it's too easy to sneak in various styles of code in all other linters. The most strict linter I know happily lets all these styles happen:
foo({ num: 3 },
1, 2)
foo(
{ num: 3 },
1, 2)
foo(
{ num: 3 },
1,
2
)
Prettier bans all custom styling by parsing it away and re-printing the parsed AST with its own rules that take the maximum line width into account, wrapping code when necessary.
Install:
yarn add prettier
You can install it globally if you like:
yarn global add prettier
We're defaulting to yarn
but you can use npm
if you like:
npm install [-g] prettier
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
. While this is in beta you
should probably commit your code before doing that.
prettier [opts] [filename ...]
For example, you could format your source using bash filename expansion:
prettier --write src/**/*.js bin/*.js
In the future we will have better support for formatting whole projects.
The API is a single function exported as format
. The options
argument is optional, and all of the defaults are shown below:
const prettier = require("prettier");
prettier.format(source, {
// Fit code within this line limit
printWidth: 80,
// Number of spaces it should use per tab
tabWidth: 2,
// Use the flow parser instead of babylon
useFlowParser: false,
// If true, will use single instead of double quotes
singleQuote: false,
// Controls the printing of trailing commas wherever possible
trailingComma: false,
// Controls the printing of spaces inside array and objects
bracketSpacing: true
});
Atom users can simply install the prettier-atom
package and use
ctrl+alt+f to format a file (or format on save if turned on).
Emacs users should see this folder for on-demand formatting.
Vim users can add the following to their .vimrc
:
autocmd FileType javascript set formatprg=prettier\ --stdin
This makes Prettier power the gq
command
for automatic formatting without any plugins.
Can be installed using the extension sidebar. Search for Prettier - JavaScript formatter
Can also be installed using ext install prettier-vscode
Check repository for configuration and shortcuts
Please see this issue for those interested in working on Sublime Text integration.
More editors are coming soon.
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
flow parser with the
useFlowParser
API or --flow-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.
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 concatentation 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. Better docs will come soon.
We will work on better docs over time, but in the mean time, here are a few notes if you are interested in contributing:
yarn
jest -u
and then
git diff
to see the styles that changed. Always update the
snapshots if opening a PR.jest -u
to update the snapshots and I see them in the PR, that's fine.AST_COMPARE=1 jest
for a more robust test run. That
formats each file, re-parses it, and compares the new AST with the
original one and makes sure they are semantically equivalent.0.0.9
defun-before-save
will use. (#276,
on export with bracket spacing off (#278),
on import with bracket spacing off (#279)FAQs
Prettier is an opinionated code formatter
The npm package prettier receives a total of 34,464,537 weekly downloads. As such, prettier popularity was classified as popular.
We found that prettier demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.