Keeping Your Code Clean With Prettier

Code formatting seems like a trivial subject, but it’s something that can affect the quality and correctness of your code, how it gets version controlled, and how you collaborate with others. If you don’t want to get bogged down in details of where every last brace goes, however, try outsourcing the problem to open-source tool, Prettier.

Formatting Matters

Software development teams have wasted countless hours throughout history arguing about maximum line length or on which line a brace should go. Whatever personal preference says, most people agree on at least one thing: code formatting should be consistent across a project.

Prettier is a tool designed to achieve this. Give it some code and it will hand back the same code, formatted in a consistent manner. Prettier has text editor integration, a command-line tool, and an online demo.

Speaking the Right Language

First of all, you’ll want to know if Prettier is compatible with the language, or languages, you typically work with. Prettier is currently focussed on a core set of languages mainly devoted to front-end web development, including:

  • JavaScript
  • HTML
  • CSS
  • Sass
  • Markdown
  • YAML

There is also open-ended support for additional languages via plugins.

Try Out Prettier Using the Online Playground

Before even trying to install Prettier, you might want to check out the playground. Using a web interface, you can paste in some example code and observe how Prettier will transform it. This is a great way of getting an impression of what the tool actually does, but it can also act as your primary method for using Prettier, if your requirements are on the lighter side.

By default, the playground should look like two basic text editor panels, one on the left for your input, one on the right showing Prettier’s output. You’ll see some sample code initially, but you can simply remove all of this and paste in your own.

For example, try entering the following JavaScript:

(function ()
{
window.alert('ok')
}())

Prettier should turn it into:

(function () {
window.alert("ok");
})();

Notice, by default, the changes that Prettier makes include:

  • Converting single-quoted strings into double-quoted ones
  • Adding semi-colons
  • Converting indents into two spaces

In the bottom left is a button allowing you to view options. With the previous example, try adjusting the tab width, toggling the –single-quote flag under Common, or toggling the –no-semi flag under JavaScript.

Configuring options

Prettier is self-described as “opinionated”, a deliberate design choice which means control of the specifics is sacrificed for simplicity and consistency. It’s designed for you to set up, then forget about, rather than remain preoccupied with every last formatting detail of your code. (For an alternative with much finer-grained control over every last formatting detail, try eslint.)

However, the authors also recognize that some decisions have functional impact beyond just how the code looks. Some options—including some for legacy purposes—remain, so you should at least understand what they do, even if you use Prettier in its default state.

The best way of managing Prettier options is to save them in a configuration file. There are many ways to organize this, but start by creating a file named .prettierrc.json in your local project directory. It can contain any of the supported options in a standard JSON object, e.g.

{
"tabWidth": 8
}

The same configuration file will be read by Prettier whether you’re running it via the command line or a supported text editor.

Basic Installation and the Command Line Tool

Using yarn or npm, installation should be straightforward. For yarn:

$ yarn global add prettier

And for npm:

$ npm install --global prettier

Once you’ve installed Prettier globally, you should be able to type:

$ prettier

By default, you’ll get a screen of help text which will confirm the tool is installed and operating correctly.

Cleaning a File

To reformat a file, use a command similar to:

$ prettier --write filename.js

This will overwrite the original file, which is often the most convenient approach. Alternatively, you might just want prettier to act on every file in a project:

$ prettier --write .

Prettier will run across all files under the current directory, formatting all those that it recognizes.

You can also print the result to standard output, rather than altering the original file, which allows you to save the output to a different file, or redirect it elsewhere:

$ prettier test.js > test2.js

Checking a File

To have Prettier report on the cleanliness of your code without actually making any changes, use the –check flag with either a single filename or many:

$ prettier --check .

You’ll get a line of output for each file that doesn’t match the expected format, according to Prettier’s configuration:

Checking formatting...
[warn] .prettierrc
[warn] .prettierrc.json
[warn] Code style issues found in the above file(s). Forgot to run Prettier?

Command Line Options

Prettier’s standard options are available as command line options, if you require them. Here’s an example of how the –single-quote flag affects output:

$ prettier tmp.js
function example() {
console.log("hello, world");
}
$ prettier --single-quote tmp.js
function example() {
console.log('hello, world');
}

Getting Help

The Command Line tool provides informative help on any option via the –help flag:

$ prettier --help trailing-comma
--trailing-comma
Print trailing commas wherever possible when multi-line.
Valid options:
es5 Trailing commas where valid in ES5 (objects, arrays, etc.)
none No trailing commas.
all Trailing commas wherever possible (including function arguments).
Default: es5

Using a Text Editor

Once you’ve installed Prettier, you can use it in a variety of scenarios, depending on what toolset you’re already using. Chances are, you use a text editor. Prettier has bindings for most of the popular ones, so here’s how to get three of them set up:

Sublime Text

JsPrettier is a Sublime Text plugin that makes Prettier available in the editor. Although there are several different ways of installing JsPrettier, we recommend using the Package Control method. You will need to have installed Prettier already, then open Sublime Text’s Command Palette and select “Package Control: Install Package”:

Then search for “jsprettier” and click to install it:

Once JsPrettier is installed, you can right-click in any open file to format it. You can also set the value of auto_format_on_save to true in JsPrettier’s settings which will result in JsPrettier automatically cleaning up any compatible files when you save them in Sublime Text.

Atom

Installation for Atom is very similar to Sublime Text: simply use the editor’s built-in package manager to install prettier-atom:

Once installed, usage is familiar: a shortcut or menu item allows you to format a file on demand, whilst an Atom setting lets you automatically run Prettier whenever a file is saved.

Vim

Vim is a very powerful, command line based editor that is not suitable for beginners. Getting Prettier to work with vim is appropriately complicated, but it’s still only a few steps:

mkdir -p ~/.vim/pack/plugins/start
git clone https://github.com/prettier/vim-prettier
~/.vim/pack/plugins/start/vim-prettier

Git is probably the easiest way to download the necessary files, but any means of getting vim-prettier into that start directory should do the job.

Once installed, Prettier will automatically run when a file is saved in vi. It can also be run manually at any time via the Prettier command:

Which should result in a cleaned file:

Integrate Prettier Into Your Project

Using a code formatter such as Prettier can help maintain a codebase that’s easier to read. It can also help to sidestep debates about which particular style to use when coding—just outsource those decisions to Prettier!

Finally, a git hook can be set up to ensure code always gets cleaned up when it’s committed to your project’s repository. Individual developers can be free to format their code however they wish, but the central copy will always be clean and consistent.

Source: makeuseof.com

Related posts

Connections #336: Today’s Answer and Clues (Sunday, May 12, 2024)

What are AI PCs, and What Makes Them Different?

I Took the Same Photos With My Phone and Camera: Which One Did It Better?