Don‘t just lint your code – fix it with Prettier

As developers, we know that linting is an important part of writing quality code. Linters analyze our source code and flag programming errors, bugs, stylistic issues, and suspicious constructs. Popular tools like ESLint help catch problems early, enforce coding standards, and keep codebases maintainable.

But while linters excel at identifying issues, the actual work of fixing those problems still falls on our shoulders. Wouldn‘t it be nice if there was a tool that could automatically remediate common linting offenses?

Enter Prettier – an "opinionated code formatter" that not only points out style inconsistencies but directly edits your code to resolve them. Let‘s take a closer look at how Prettier works and how it can turbocharge your code quality workflow when paired with a linter like ESLint.

What is linting?

Before diving into Prettier, let‘s do a quick refresher on linting and why it‘s so valuable. Linting refers to the process of running a program that analyzes code for potential errors. Modern linters like ESLint use static code analysis to evaluate source code without actually executing it.

Linters serve as a first line of defense against bugs and anti-patterns. They scour codebases for common gotchas like syntax errors, undeclared variables, invalid formatting, and dangerous coding practices. Many linters are configurable, allowing development teams to define their preferred coding style and conventions.

The benefits of linting include:

  • Catching bugs and errors early in the development process
  • Ensuring code consistency and readability
  • Avoiding dangerous anti-patterns and bad practices
  • Adhering to coding standards across teams and projects
  • Saving time and effort in code reviews

While virtually all programming languages have linters available, some of the most prominent are ESLint, JSHint, and TSLint for JavaScript, RuboCop for Ruby, Pylint for Python, and SonarLint for Java.

Introducing Prettier

Prettier is a cutting-edge code formatter that enforces a consistent style throughout your codebase. It‘s not a traditional linter that just identifies issues – instead, Prettier actually rewrites your code to adhere to its formatting rules.

With Prettier, you no longer have to waste time manually fixing linting errors and debating stylistic preferences like spacing, semicolons, and line breaks. Simply run Prettier on your code and it will automatically format it according to a sensible, consistent style.

Some key features of Prettier:

  • Supports many languages including JavaScript, TypeScript, HTML, CSS, JSON, GraphQL, Markdown, and YAML
  • Integrates with most code editors for easy setup and use
  • Highly opinionated with minimal configuration options
  • Focus is on code formatting, not catching bugs or quality issues
  • Can be used standalone or in conjunction with linters

Prettier was created by James Long in 2017 when he grew frustrated with the endless style debates and bikeshedding that plague development teams. The goal was to create an opinionated formatter that favored a rigid and specific code style.

While this inflexibility may seem like a downside, in practice it eliminates time wasted on petty arguments and frees developers to focus on actual coding. Prettier‘s opinionated nature makes it especially well-suited for teams that struggle withreachingconsensus on stylistic choices.

Prettier logo

How Prettier works

So how exactly does Prettier consistently format our messy code? Under the hood, Prettier uses a sophisticated multi-step process:

  1. Prettier parses your source code into an Abstract Syntax Tree (AST)
  2. It then traverses the AST, applying formatting rules at each node
  3. Finally, Prettier reconstitutes the AST into properly formatted code

This approach allows Prettier to understand code structure rather than blindly manipulating strings of text. By working with an AST, Prettier can intelligently and safely edit code without introducing errors.

When run, Prettier outputs the reformatted code either back to the same file or to a new one, depending on the configuration. Developers can run Prettier through its CLI, code editor plugins, or via an API in code.

One potential "gotcha" with Prettier is that its changes are quite extensive. It‘s not uncommon for Prettier to completely alter the style and layout of your existing code upon first run. This can cause some initial shock and resistance from developers attached to their personal coding style.

However, this short-term pain is far outweighed by the long-term gain of never having to worry about code formatting again. Plus, Prettier‘s peerless consistency makes reading co-worker‘s code feel like reading your own.

Setting up Prettier with ESLint

While Prettier can be used standalone, its real power shines when integrated with a traditional linter like ESLint. Combining these tools creates a formidable code quality duo – Prettier handles the formatting while ESLint focuses on catching logic errors and bad practices.

To demonstrate, let‘s walk through setting up Prettier and ESLint in a JavaScript project. We‘ll assume you already have ESLint installed and configured.

First, install the necessary dependencies:

yarn add --dev prettier eslint-config-prettier eslint-plugin-prettier

Or if you prefer npm:

npm install --save-dev prettier eslint-config-prettier eslint-plugin-prettier

Here‘s what each package does:

  • prettier: The core Prettier library and CLI
  • eslint-config-prettier: Disables ESLint rules that conflict with Prettier
  • eslint-plugin-prettier: Runs Prettier as an ESLint rule

Next, update your .eslintrc configuration file:

{
  "extends": ["plugin:prettier/recommended"]
}

This one line does a few important things:

  1. Enables eslint-plugin-prettier to run Prettier as an ESLint rule
  2. Extends the eslint-config-prettier config to disable conflicting rules
  3. Displays prettier errors as ESLint errors

And that‘s it! With this setup, ESLint will now check your code formatting using Prettier‘s rules. Any style violations will be flagged as ESLint errors for you to fix.

Configuring Prettier

By design, Prettier favors convention over configuration. It intentionally provides very few options to minimize bikeshedding and make adoption painless.

However, you can still customize some aspects of Prettier‘s output by creating a .prettierrc config file. Here you can change settings like tab width, semicolons, quotes, and bracket spacing.

A sample .prettierrc file might look like:

{
  "printWidth": 100,
  "tabWidth": 2,
  "useTabs": false,  
  "semi": true,
  "singleQuote": true,
  "trailingComma": "es5",
  "bracketSpacing": false
}

These options would:

  • Set the print width to 100 characters
  • Use 2 spaces for indentation
  • Avoid using tab characters
  • Add semicolons at the end of statements
  • Use single quotes instead of double quotes
  • Add trailing commas where valid in ES5
  • Remove spaces between brackets and their contents

Keep in mind that Prettier‘s goal is to provide a consistent, opinionated style. While you can customize some formatting preferences, don‘t expect unlimited flexibility or the ability to match your project‘s existing style exactly.

The Prettier team strongly encourages using the default settings and only changing options when absolutely necessary. Limiting config options helps avoid heated debates and ensures codebases remain consistent across projects and teams.

New code formatting and linting workflow

With Prettier and ESLint working harmoniously, your code quality workflow should look something like this:

  1. Write your code without worrying about formatting
  2. Run Prettier to reformat your code to a consistent style
  3. Run ESLint to catch any remaining logic errors or bad practices
  4. Fix ESLint errors and repeat until your code passes linting
  5. Commit your code with confidence

You can run Prettier and ESLint through their respective CLIs, editor plugins, or npm scripts. For maximum efficiency, set up npm scripts in your package.json:

{
  "scripts": {
    "format": "prettier --write src/**/*.js",
    "lint": "eslint src/**/*.js",
    "lint:fix": "eslint src/**/*.js --fix"
  }
}

Now you can format and lint from the command line:

# Format code with Prettier
yarn format

# Lint and autofix with ESLint 
yarn lint:fix 

By separating formatting from linting, you keep each tool focused on what it does best. Let Prettier handle the style and let ESLint handle the substance.

Next steps – pre-commit hook

Want to enforce properly formatted, linted code on every commit? Stay tuned for the next post where we‘ll set up a pre-commit hook to automatically run Prettier and ESLint. Never let unformatted or problematic code sneak into your repo again!

coding magic

Conclusion

Linters are invaluable tools for maintaining code quality and consistency. However, manually fixing every single formatting error can be a tedious time-sink. Prettier solves this problem by automatically formatting your code to a sensible, consistent style.

Prettier‘s opinionated nature eliminates bikeshedding and ensures all code is formatted uniformly across projects and teams. By integrating Prettier with a traditional linter like ESLint, you get the best of both worlds – consistent style and substantive code quality checks.

Adopting Prettier in your development workflow will save countless hours wasted on style nit-picking. Set it up once and let Prettier handle the formatting so you can focus on the actual business logic. With tools like ESLint and Prettier on your side, you can ship cleaner, more maintainable code faster.

Happy linting!

happy linting meme

Similar Posts