Become a member
to unlock all features

Level Up!



    Fix Only Committed Files with Prettier and lint-staged


    In this lesson we'll use prettier and lint-staged to run prettier only on files that have been changed and committed to git. This will allow you to prettify files as you change them, and prevent massive lint only git check ins.



    Become a Member to view code

    You must be a Pro Member to view code


    Become a Member
    and unlock code for this lesson
    orLog In




    Prettier is an opinionated formatting tool that allows you to format JavaScript of any kind as well as CSS. It is rivaled because it has many sane defaults and not many configurations. To get started, we'll install Prettier, lint-staged, and Husky to our devDependencies.

    Once complete, we'll go to our package.json, and we'll set up a script. The script will be the pre-commit hook, and we'll run lint-staged. This pre-commit hook is configured by Husky, and is configured inside of the Git script so that when a commit happens, this command will be run.

    Now, we'll set up our lint-staged configuration. We'll add lint-staged here, which will receive an object. Then it will ask for what types of files that we want to format. We'll say *.js, which will then also receive an array.

    This array will be the commands that we want to run. There'll be two. We'll want to run prettier--right. Then the final command will be git add, which will then add the files after Prettier has run. With this configuration, we'll only run Prettier on the files that have changed.

    This means that we will gradually be able to prettify our code base, rather than having a huge Git check-in of a bunch of prettified code. To prove that it is only working on our stage files that we're committing, we have created two files.

    One, index.js, with a bunch of white space here, as well as a separate file with a bunch of white space. If we go into our Git with VS code, we can see that there's two files that have changed. We will simply stage this index.js, add a commit message, and then when we commit it.

    If we go back, we can see that the white space is now gone, however this other file that we did not commit still has its white space.