Prettier and saving time
Table of contents:
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.
You're spending too much time in the age-old question: spaces or tabs? pic.twitter.com/pdnoErTYkT
— Chris Hinds Denver City Council (@DenverPerfect10) August 3, 2020
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.
Spending too much time in code reviews on tabs vs. spaces? Leave your JavaScript formatting to Prettier 1.0: https://t.co/2Sv1vMpOEA pic.twitter.com/0Ydsyf8so1
— GitHub (@github) April 14, 2017
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:
There are many available options, can be checked here.
You can also choose which files to ignore with a .prettierignore
:
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:
- style-components
- Prettier
- Prettier 2.4: new bracketSameLine option and TypeScript 4.4 support!
- Prettier - Code formatter
- prettier npm package
My site is free of ads and trackers. Was this post helpful to you? Why not
Disqus is great for comments/feedback but I had no idea it came with these gaudy ads.