(Angular) Globally enforce a coding style using TSLint + Prettier + Husky


Globally enforce an Angular app code style by combining the power of Husky and Prettier

Here's how to automate and enforce a global coding styling so that you and your developers can focus on what matters.

Introduction

Automation is a HUGE key in accelerating any Angular project.

So why not automate the way our Angular code is formatted and globally enforce a code style? As well as use TSLint to check for errors before some virgin programmer comes along and tries to commit something that should never be allowed in the repository?

Not to mention that once a global coding style is enforced there'll be fewer bombastic arguments or gabby emails about exactly how this new piece of code should be formatted.

Yes my friend, this is what exceptional Angular devs do. We automate the easy parts and focus on the essentials while others burns hours motormouthing their opinionated thoughts.

So sit up and start licking your chops buddy! We're going to automate the easy part of code format and basic Angular best practices so that we can focus on what matters.

Requirements

We'll need to make sure that we've got the latest version of npm installed. Otherwise it's likely to throw some red-headed-screech-owl error when we start installing our tools.

To update run the following command.

  • npm install npm@latest -g

Install Instructions

We'll begin by installing the needed tools. In the root directory of your Angular project type the following commands

  • npm i --save-dev husky prettier pretty-quick

Configure Husky

First step is to configure Husky to run Prettier and TSLint every time a new commit is about to be made.

In the root directory of your project open the package.json file and add the following config to the bottom of the file.

  "husky": {
    "hooks": {
      "pre-commit": "pretty-quick --staged & ng lint"
    }
  }

Testing Results

Let's take a component and make it look really ugly.

We'll go ahead and try to commit it... but.. bang! Husky catches it.

Now if we check the file we'll see how Prettier kicked in and formatted the code.

Conclusion

And now that this is automated there's no need to worry about it anymore. Screw those useless water fountain discussions about using spaces or tabs!

Let's get back to work and focus on the essentials.

Angular Consultant