Code Review Videos > JavaScript & TypeScript > Consistent Code Formatting with Prettier

Consistent Code Formatting with Prettier

Welcome to our journey into the world of code formatting with Prettier for UK Government NodeJS projects.

As budding developers, we all know the thrill of bringing our ideas to life through code. Yet, as we dive deeper into the realms of web development, we quickly discover that writing code is just the beginning. Ensuring that our code remains clean, consistent, and adheres to agreed standards set by the wider team on UK Government projects can seem like a daunting task.

In this article, we will look at the most common way to automatically keep our code formatting consistent and how Prettier can become our trusty sidekick in this quest.

One less thing to worry about when submitting a PR, right?

Understanding the Significance of Code Formatting

In our coding adventures, we often find ourselves engrossed in the thrill of solving complex problems, crafting elegant solutions, and building amazing features.

However, there’s an essential aspect of creating software when working within a team bigger than a solo developer that sometimes doesn’t get the attention it truly deserves: code formatting.

Why Does Code Formatting Matter?

Picture this: You’re working on a team project for a UK Government website, aiming to deliver a secure and efficient application. Each developer on the team writes code in their unique style – some prefer tabs, others adore spaces; some like curly braces on a new line, while others prefer them snugly beside their code.

This diversity in coding styles can quickly lead to chaos and hinder collaboration.

If you’ve ever experienced the PR process grind to a halt because of stylistic differences, then you know exactly what we’re talking about.

This is where automated code formatting comes to the rescue!

Code formatting refers to the consistent arrangement and styling of code. It’s not just about aesthetics; it plays a vital role in the readability and maintainability of your codebase. Here’s why it’s so significant:

  1. Readability: Well-formatted code is like a well-organised book. It’s easier for both you and your fellow developers to read and understand. Think of it as a clear map that guides you through the intricacies of your code.
  2. Collaboration: When you’re working in a team, having a uniform code style is like speaking the same language. It fosters seamless collaboration, as everyone can easily comprehend and work with the code.
  3. Error Reduction: Properly formatted code reduces the chances of syntax errors and logical mistakes. It helps you spot issues more quickly, which is especially crucial in high-stakes projects like those for the UK Government.
  4. Maintenance: Code isn’t static; it evolves over time. When you revisit your code weeks or months later, well-formatted code makes it easier to make changes and improvements without introducing new bugs.
  5. Compliance: In projects for the UK Government, adhering to coding standards is not just a preference but a requirement. Consistent code formatting is often a part of these standards, ensuring that your code complies with the project’s guidelines and security measures.

Challenges of Inconsistent Formatting

On the flip side, inconsistent code formatting can lead to a host of issues:

  • Confusion: It’s easy to get lost in a sea of mismatched code styles, leading to confusion and frustration.
  • Wasted Time: Developers may spend precious time arguing over code style instead of solving real problems.
  • Maintenance Nightmare: Maintaining a codebase with inconsistent formatting can become a never-ending battle.

As we delve deeper into the intricacies of UK Government Express projects, you’ll realise how vital code formatting is for ensuring the reliability and security of your applications.

But don’t worry, we’re not alone on this journey.

Prettier, JavaScript’s trusty automated code formatting tool, is here to help us navigate the challenges and make our coding lives more enjoyable. So, let’s continue our exploration and learn how Prettier can be our ally in maintaining clean and consistent code for our project.

Introducing Prettier

Everyone has opinions about how code should be formatted. I know I have mine.

Some projects that I work on, I feel right at home with the way the code looks and feels.

On other projects, their choices leave me scratching my head. No semicolons? Are you bonkers?

However, opinions are just that. Through the magic of Prettier, our personal choices for formatting are largely irrelevant. This automated tool will review our code as it is created, and convert it to the code formatting style dictated by the project’s configuration.

It might sound a little draconian, but Prettier removes one extra thing that we need to think about, and ensures any code created by any developer adheres to the exact same look and feel.

Let’s take a closer look at this invaluable tool.

What is Prettier?

Prettier is a code formatting tool that aims to make your code beautiful and consistent without the need for endless debates about coding style. It’s like having a digital code beautician at your service. Prettier can automatically format your code according to a set of predefined rules, ensuring that it adheres to consistent formatting standards.

Key Features of Prettier

Prettier comes packed with features that make it a developer’s best friend:

  • Automatic Formatting: Prettier does the heavy lifting for you. Just write your code as you normally would, and Prettier takes care of the formatting automatically.
  • Wide Language Support: While our focus is on JavaScript and TypeScript, Prettier supports various programming languages, making it versatile for different project needs.
  • Configurability: While it has sensible defaults, you can configure Prettier to match specific coding standards, including those required for UK Government projects.
  • Integration: Prettier seamlessly integrates with popular code editors and IDEs, making it easy to incorporate into your workflow.
  • Command Line Interface (CLI): Prettier provides a command-line interface for those who prefer working from the terminal.
  • Community and Popularity: Prettier is widely adopted by the development community and is actively maintained, ensuring that it stays up-to-date with the latest coding standards.

Why Prettier?

You might wonder why we’ve chosen Prettier as our code formatting tool of choice. The answer is simple: Prettier removes the burden of manual formatting and the endless debates over code style, allowing us to focus on what really matters – building secure and efficient web applications that meet the requirements of the end user.

With Prettier, we can spend less time worrying about tabs vs. spaces or where to place our curly braces and more time solving critical problems and improving our codebase. It’s a game-changer for developers, especially those working on large, collaborative projects.

In the next section, we’ll dive into the practical aspects of setting up Prettier for our UK Government Express projects. We’ll show you how to make this tool work for you, ensuring your code adheres to the highest standards effortlessly.

Setting Up Prettier for Express Projects

Now that we’ve met our code formatting friend, Prettier, it’s time to put it to work in our UK Government Express projects.

Let’s roll up our sleeves and get started.

Example Project Setup

For this example, we will make use of the Gov UK Frontend Express Starter.

git clone git@github.com:codereviewvideos/example-gov-uk-frontend.git
cd example-gov-uk-frontend
npm installCode language: PHP (php)

This will give you a working Node and Express starting point.

You are, of course, free to use any JavaScript / TypeScript project you like.

Installing Prettier

Setting up Prettier is a breeze. We can install it in our project using npm or yarn, depending on your preferred package manager. Open your project’s terminal and run the following command:

npm install --save-dev prettier

This command installs Prettier as a development dependency in your project.

After doing this, your package.json should look something like this:

{
  "name": "example-gov-uk-frontend",
  "version": "1.0.0",
  "description": "The front end for an interesting Gov UK service",
  "main": "index.js",
  "scripts": {
    "build:sass": "sass --quiet-deps --load-path=node_modules/govuk-frontend --load-path=. assets/main.scss dist/public/stylesheets/main.css --style=compressed --no-source-map",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "govuk-frontend": "^4.7.0",
    "nunjucks": "^3.2.4"
  },
  "devDependencies": {
    "@types/express": "^4.17.18",
    "@types/node": "^20.7.1",
    "@types/nunjucks": "^3.2.4",
    "prettier": "^3.0.3",
    "sass": "^1.68.0",
    "typescript": "^5.2.2"
  }
}
Code language: JSON / JSON with Comments (json)

Prettier is a fast moving project that receives a lot of updates, so your version may differ from mine. That is fine.

Setting Up Our Test File

You only need to install Prettier as a development dependency in your project. Further customisation can (and will) be added, but for now, let’s see it in action.

You may have existing JavaScript and / or TypeScript code that is … messy.

If you do, feel free to use that as your example file(s).

If you don’t, grab this mess:

// Poorly formatted TypeScript code
const fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];

function calculateTotalPrice(
  item: string,
  price: number
) {
return item === 'Apple' ? price * 1.1 :
item === 'Banana' ? price * 0.9 :
item === 'Cherry' ? price * 1.2 :
item === 'Date' ? price * 1.3 :
price;
}

interface Person {
name:string;
age: number;
occupation:string
}

const person:Person = { name: 'John',age:25,occupation: 'Engineer'};
console.log(person);Code language: TypeScript (typescript)

Then create a new file in your src directory called example.ts or similar, and paste those contents in.

Your IDE might actually try to save you here. WebStorm, the IDE I use, automatically applies some formatting when pasting in:

To get the maximum benefit of this, paste in as plain text:

webstorm paste as plain text

Which should give the much more horrible:

paste as plain text result before prettier

🤮🤮🤮

Perfect.

Running Prettier With Provided Defaults

Before we make any actual changes, we can do a ‘dry run’ of Prettier direct from the commandline.

./node_modules/.bin/prettier src/example.tsCode language: Shell Session (shell)

This should immediately print out what would happen, if we were to write these changes to the file:

prettier dry run example

Even without syntax highlighting, this already looks far nicer than what we started with.

Saving Prettier Code Formatting Results

Assuming we are happy with how this file will look, we can then save (or write) the changes directly over the top of the file.

./node_modules/.bin/prettier --write src/example.tsCode language: Shell Session (shell)

The extra flag is --write, which should output the name of the file again to your commandline and the length of time it took to run. An interesting, if rather useless metric.

Back in the IDE you should now see the file updated:

prettier styled file in the IDE

Really nice.

After running Prettier on the poorly formatted TypeScript file, the code will be automatically reformatted to address these issues.

Formatting Improvements by Prettier:

  1. Consistent Indentation: Prettier ensures that the entire codebase uses consistent indentation (in this case, two spaces).
  2. Proper Spacing: Prettier adds spaces where needed, ensuring consistent spacing around operators and after commas.
  3. Function Formatting: Prettier aligns the return statement and conditional expressions, making the code more readable.
  4. Semicolons: Prettier automatically adds semicolons where necessary to ensure JavaScript’s proper behaviour.
  5. Interface and Object Literal Formatting: Prettier aligns properties within the Person interface and the person object literal, improving readability.

These automatic formatting improvements not only make the code easier to read but also ensure that it adheres to a consistent coding style, which is particularly important in collaborative projects like those for UK Government Express applications.

Of course we don’t want to be doing this manual process every single time we make a change.

And fortunately we don’t have too. Prettier is so well supported by now that practically every modern IDE or editor will have some kind of Prettier plugin functionality to automatically run Prettier every time you make a change.

Integrating with Your Code Editor

To make your life even easier, consider integrating Prettier with your code editor or IDE. Most modern code editors support Prettier plugins or extensions that can automatically format your code as you write it. This ensures that your code stays consistent without you even needing to think about it.

Whether you’re using Visual Studio Code, WebStorm, Sublime Text, or another popular code editor, there’s likely a Prettier extension available to streamline the process.

I made a post about configuring WebStorm to run Prettier on save, and one problem you might commonly encounter when setting this up.

In the next section, we’ll delve into Prettier best practices tailored for UK Government Express projects. We’ll explore how to ensure our code adheres to the strict standards required by government projects while keeping our development process smooth and efficient.

Configuring Prettier

While Prettier has sensible default settings, you may want to configure it to match the coding standards agreed by your team when working on UK Government projects.

Prettier uses cosmiconfig for configuration file support. This means you can configure Prettier in a number of ways.

Most commonly, in my working experience, is the use of a .prettierrc file in the root of our project. This file can be written as JSON or YAML, though again in my personal experience this has always been JSON, and allows us to define our preferred formatting rules.

Here’s a basic example:

{
  "semi": false,
  "singleQuote": true,
  "trailingComma": "none"
}Code language: JSON / JSON with Comments (json)

As I said right back at the start of this post, you may actually disagree with these rules. That’s absolutely fine. These are not my personal favourites, either.

So, why would I use them as my example?

Because they come from the .prettierrc.js (a different but equally valid way of configuring Prettier code formatting rules) from the govuk-frontend code repository.

Being the library that practically all UK Gov projects will import, these rules are fairly common to see adopted.

gov uk prettier code styling applied

This isn’t to say you must adopt these styles for your Gov UK project. It’s just that they are more common because of people copying from the styles set ‘upstream’.

Automating Code Formatting with Prettier

One of the key advantages of Prettier is its ability to automate code formatting, ensuring that you and your team’s code adheres to coding standards without manual intervention.

In this section, we’ll explore a few common ways to seamlessly integrate Prettier into your workflow using popular tools like ESLint and Git hooks.

Integrating Prettier with ESLint

ESLint is a widely used static code analysis tool that helps identify and fix issues in your JavaScript or TypeScript code. By combining ESLint with Prettier, you can enforce code formatting and catch potential errors simultaneously.

Here’s how to set up ESLint to work in tandem with Prettier:

Install ESLint

First, install the ESLint as a development dependency in your project:

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

Let’s break down what each package does:

  1. eslint: This package installs ESLint, which is a widely used static code analysis tool for JavaScript and TypeScript. ESLint helps you find and fix issues in your code by enforcing coding style rules and identifying potential errors.
  2. eslint-plugin-prettier: This package is an ESLint plugin that integrates ESLint with Prettier, the code formatting tool. It allows ESLint to check your code for formatting issues according to Prettier’s rules.
  3. eslint-config-prettier: This package provides an ESLint configuration that disables all ESLint rules that are unnecessary or might conflict with Prettier. Essentially, it ensures that ESLint doesn’t interfere with Prettier’s code formatting.

When you run this command and install these packages as development dependencies, you’re setting up your project to use ESLint in conjunction with Prettier. This combination helps you enforce code formatting standards and identify potential issues in your code, all while ensuring that Prettier handles the actual code formatting.

Configure ESLint

Create an ESLint configuration file (e.g., .eslintrc.js) and extend the Prettier plugin:

module.exports = {
  extends: ['plugin:prettier/recommended'],
};Code language: JavaScript (javascript)

This configuration ensures that ESLint checks your code for formatting issues using Prettier’s rules.

You are complete free to customise this file however you like.

If you’re looking for a starting point, once again consider the govuk-frontend and how they structure theirs.

Editor Integration

To maintain consistent formatting as you write code, consider enabling ESLint and Prettier integrations in your code editor or IDE.

These integrations provide real-time feedback and auto-formatting.

We covered this above.

Another useful file to add to the root of your project is the .editorconfig.

The .editorconfig file is used to define and maintain consistent coding styles and formatting settings across different code editors and IDEs within a project or across multiple projects. It helps developers and teams ensure that the codebase adheres to a unified set of coding standards, including aspects like indentation, line endings, and character encoding.

Here are the key purposes and benefits of using an .editorconfig file:

  1. Consistency: .editorconfig ensures that all team members and contributors use the same code formatting settings, promoting code consistency and readability. This consistency is particularly important in collaborative projects.
  2. Cross-Editor Compatibility: Different code editors and IDEs may have their own default formatting settings. An .editorconfig file overrides these defaults, ensuring that the code looks the same regardless of the editor used by individual developers.
  3. Project Portability: When sharing code with others or moving projects between different development environments, the .editorconfig file makes it easier to maintain the same code formatting without manual adjustments.
  4. Ease of Configuration: Developers can easily configure and customise coding style settings for their preferred code editor by referring to the .editorconfig file, reducing the need for complex editor-specific settings.
  5. Multiple Project Support: If you work on multiple projects with different coding standards, you can have separate .editorconfig files in each project, allowing you to switch between coding styles seamlessly.
  6. Linting Integration: .editorconfig can be used in conjunction with linters (e.g., ESLint) and code formatting tools (e.g., Prettier) to ensure that code adheres to both coding standards and formatting rules.

Here’s an example of what an .editorconfig file might look like:

# Top-level properties apply to all files in the project
root = true

# Set the character encoding to UTF-8
[*]
charset = utf-8

# Use LF (Unix-style) line endings
[*]
end_of_line = lf

# Use 2 spaces for indentation in JavaScript and TypeScript files
[*.js]
indent_style = space
indent_size = 2

[*.ts]
indent_style = space
indent_size = 2

# Add Nunjucks styles from the govuk-frontend
[*.njk]
indent_size = 2
indent_style = space
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = trueCode language: PHP (php)

In this example, the .editorconfig file defines settings for character encoding, line endings, and indentation style and size. These settings will apply to all JavaScript and TypeScript files in the project.

Once again, the govuk-frontend has a useful .editorconfig file to start from.

By using an .editorconfig file, you can ensure that your codebase maintains a consistent and standardised coding style, making it more readable and maintainable for all contributors to the project.

CI / CD Integration

CI/CD stands for Continuous Integration and Continuous Deployment (or Continuous Delivery). It is a set of practices and tools used in software development to automate the building, testing, and deployment of code changes.

CI/CD pipelines ensure that code changes are thoroughly tested and validated before being deployed to production or merged into the main branch of a code repository.

In the context of enforcing code formatting and linting rules, CI/CD integration means incorporating these checks into the automated pipeline. This ensures that code changes go through a series of automated checks, including code formatting and linting, before they are allowed to be merged into the main branch.

If the code changes do not meet these standards, the pipeline will reject them, preventing the introduction of poorly formatted or problematic code into the project.

Example Scripts For Checking Your Code Formatting In CI

Here are example lint:check and format:check scripts that you could include in your package.json file:

{
  "scripts": {
    "lint:check": "eslint . --max-warnings=0",
    "format:check": "prettier --check ."
  }
}Code language: JSON / JSON with Comments (json)
  1. lint:check: This script uses ESLint to check your code for linting errors. The --max-warnings=0 flag ensures that ESLint treats any warnings as errors, so it fails if there are any linting issues. The . argument specifies that ESLint should check all files in the current directory and its subdirectories.
  2. format:check: This script uses Prettier to check if your code adheres to the formatting rules defined in your Prettier configuration (e.g., .prettierrc). The --check flag tells Prettier to check the code without making any changes. The . argument specifies that Prettier should check all files in the current directory and its subdirectories.

If we ran these scripts on our poorly formatted code in example.ts from earlier, we would see:

gov-uk-code-formatting-example git:(main)npm run lint:check

> example-gov-uk-frontend@1.0.0 lint:check
> eslint . --max-warnings=0

➜  gov-uk-code-formatting-example git:(main) ✗ npm run format:check

> example-gov-uk-frontend@1.0.0 format:check
> prettier --check .

Checking formatting...
[warn] .prettierrc
[warn] assets/main.scss
[warn] Readme.md
[warn] src/index.ts
[warn] tsconfig.json
[warn] Code style issues found in 5 files. Run Prettier to fix.Code language: CSS (css)

With these scripts in your package.json, you can run npm run lint:check to check for linting errors and npm run format:check to check code formatting compliance in your project. These checks can be integrated into your CI/CD pipeline to ensure code quality and consistent formatting.

Example GitHub Actions Configuration

GitHub Actions is a popular CI/CD platform provided by GitHub.

You can use it to create workflows that automate various tasks, including code formatting and linting checks.

Below is an example GitHub Actions configuration (.github/workflows/ci.yml) that rejects a pull request (PR) if the code formatting rules, as enforced by Prettier, are not met:

name: CI

on:
  pull_request:
    branches:
      - main

jobs:
  lint-and-format:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      - name: Install Node.js
        uses: actions/setup-node@v2
        with:
          node-version: 18

      - name: Install dependencies
        run: npm install

      - name: Run ESLint and Prettier
        run: npm run lint:check && npm run format:check

      - name: Create status check
        id: status
        run: echo "Code formatting and linting checks passed."Code language: PHP (php)

And how this might look in GitHub after opening the PR:

github failing PR due to code formatting

This approach is a last line of defence. Developers may opt not to run their code formatting before making a change, but you can force them to fix up their code if they want their PR to be merged.

Conclusion

Congratulations, you’ve now embarked on a journey through the world of code formatting and Prettier for your UK Government Express projects. In this article, we’ve covered essential concepts, best practices, and practical steps to help you maintain code consistency, readability, and easier collaboration with all your team members.

Code formatting is not just about aesthetics; it’s a vital aspect of producing high-quality, maintainable code. Prettier, with its automation capabilities, makes this task easier, allowing you to focus on what matters most: writing great code that solves real user needs.

Here’s a quick recap of what we’ve covered:

  • Getting Started: We introduced Prettier, discussed its benefits, and showed you how to set it up in your project.
  • Prettier Best Practices: We explored best practices for configuring Prettier to align with UK Government coding standards and how to enforce these practices in your team.
  • Automating Code Formatting: You learned how to automate code formatting using tools like ESLint and Git hooks, ensuring code consistency throughout your development workflow.
  • CI/CD Integration: We demonstrated how to incorporate Prettier checks into your CI/CD pipeline, preventing code changes that do not adhere to formatting and linting rules from reaching the main branch.

By embracing code formatting practices and integrating Prettier into your development process, you’re not only contributing to the overall quality of your UK Government Express projects but also positioning yourself as a developer who values clean and maintainable code.

Remember that coding standards and best practices are not static; they evolve over time. Stay updated with the latest developments in coding standards, and regularly review and adapt your code formatting rules to keep pace with industry trends.

As you continue your journey in JavaScript, TypeScript, React, Node.js, and all the other exciting technologies you’re exploring, keep Prettier by your side as a trusted ally in your quest for code perfection.

Happy coding, and may your UK Government Express projects shine with beautifully formatted code!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.