Table of contents:

  1. What is prettier?
  2. Code formatters
  3. Prettier
  4. How to use it?
  5. How does prettier work?

What is prettier?

Prettier is a code formatter for JavaScript, with support for: JSX, CSS, Less, SCSS, Angular, Vue, Flow, TypeScript, HTML, JSON, GraphQL, YAML, MDX, Markdown, GFM.

Spaces of tabs? If you’re a developer, you probably know what I’m talking about if you are not aware that these questions are the impulse to heated debates within each development team.

Some of those debates can be a complete waste of time but are important. Code style should be respected, this makes it easier for everyone to work and move forward, solve more complex problems … Coding like a compulsive maniac for some time can cause us to forget about certain rules.

Code formatters

Many languages provide a code formatters. For example goftm for Go, rustftm for Rust, Black in Python. This is quite simple, just run the command on your file and the code is formatted according to some rules. While using code formatter for the first time, some of us are confused and more likely frustrated, but after a while, we can trust it.

Using code formatter save time, time that you can use for code development. Easy to set up, share between all members of the team. If you even use develop your pet project to build your first unicorn startup which will rock to the moon ;), it’s really worth it.

Prettier

Prettier become a formatter for JavaScript with support of JSX, CSS, GraphQL and style components, project quickly gained popularity, especially among front-end developers.

How to use it?

There are plugins for all editors: Visual Studio Code, Sublime Text, Vim … After installing the plugin we can modify some parameters, for example:

  • line length
  • tabulator or spaces
  • semicolons
  • single or double quotes
  • commas

To use prittier to project just add .prettierrc to the root of thr project and define rules:

{
  "trailingComma": "es6",
  "singleQuote": true
}

There are many available options, can be checked here. You can also choose which files to ignore with a .prettierignore:

dist/
package.json

How does prettier work?

Prettier generates an AST and rebuilds a code based on the rules you have chosen using babel-parser, the Babel AST generator. Abstract Syntax Tree is a tree representation of a code, to understand what it is you can take a look at AST Explorer.

Prittier is open source and the code can be read here.


Reference:

  1. style-components
  2. Prettier
  3. Prettier 2.4: new bracketSameLine option and TypeScript 4.4 support!
  4. Prettier - Code formatter
  5. prettier npm package