Prettify your codebase automatically

Suman Kunwar
3 min readJan 19, 2019

--

While working in a team with a large codebase, putting a consistent style guide is always a challenging task. With the numbers of increasing, Text Editor, IDE and the various flavors of style guides gives flexibility to the developers and helps them to accomplish their task in a convenient way but sometimes it becomes troublesome too.

As the codebase becomes huge along with the increasing number of people in a project, the conflict between choosing a style guide or IDE always arises. While pushing our work, it will be nice if our code is readable and maintainable to others. There might be a case when we push our work to the repository and it not well-indented or prettified.

Prettier is an opinionated code formatter with support for JSON, HTML, Angular, YAML and many more. Prettier enforces a consistent code style (i.e. code formatting that won’t affect the AST) across your entire codebase because it disregards the original styling by parsing it away and re-printing the parsed AST with its own rules that take the maximum line length into account, wrapping code when necessary(See this blog post).

We are going to take the help of Prettier pre-commit tool to re-format our files that are marked as “staged” via git addbefore you commit.

Install it along with husky:

yarn add eslint eslint-config-prettier husky lint-staged prettier --dev

and add this config to your package.json:

"scripts": {     "precommit": "lint-staged",     "format": "prettier --write \"**/*.+ .        (js|md|html|ts|css|sass|less|graphql|yml|yaml|scss|json|vue)\""},

Here we are defining two different scripts one is precommit and next is format. The format command runs the prettier which the matching regular expression files and the resulting output is prettified. The other command precommit is used here to configure the lint-staged which helps to Run linters against staged git files. It can be configured in other ways too (see here).

Our lint-staged.config.jslooks like this:

.prettierrc and .eslintric are defined as follows:

.prettierrc defined the set of rules for the prettifier whereas .eslintric is used to define config for prettier.

So now let's take an example of index.js.

console.log(one);console.log('hello')[1, 2, 3].forEach(() => {})

If we add a git commit then we can see the errors:

After fixing it:

And if we look at theindex.js file:

var one = 1console.log(one)console.log('hello')[(1, 2, 3)].forEach(() => {})

we can see there are no trailing commas and the function of an array is enclosed in [].

In this way, with the help of precommit, we can prettify our codebase irrespective of the editor of IDE’s config. Which saves time and makes our development fast and readable codebase.

Source Code

--

--

Suman Kunwar
Suman Kunwar

Written by Suman Kunwar

Innovating Sustainability | Researcher | Author of Learn JavaScript : Beginners Edition

No responses yet