pre & post install 🛠️ script, husky 🐕, lifecycle scripts ♻️

By Prajwal Haniya

Techletter #86 | August 17, 2024

What is the use of preinstall and postinstall scripts in package.json?

The preinstall and postinstall scripts in package.json are part of the npm lifecycle scripts that allow developers to execute specific commands before and after the installation of a package, respectively.

The preinstall script is executed before the package is installed. This can be useful for several purposes, such as:

The postinstall script runs immediately after the package has been installed. Its uses include:


What is husky?

Husky is an npm package that simplifies the use of Git hooks in JavaScript/TypeScript projects. Git hooks are scripts that Git executes automatically at certain points in the Git workflow, such as before committing or pushing changes. By using Husky, developers can automate various tasks to maintain code quality and consistency across their projects.

How to use husky?

First install husky and then add pre-commit

husky install

Now I have written a script that does everything for me

#!/bin/sh

# Check if the .husky directory exists
if [ ! -d ".husky" ]; then
    echo "Creating .husky directory..."
    mkdir .husky
fi

# Check if the pre-commit file exists
if [ ! -f ".husky/pre-commit" ]; then
    rm -rf ./.husky/*
    echo "Creating pre-commit file..."
    touch .husky/pre-commit
    echo '#!/bin/sh' > .husky/pre-commit
    echo 'yarn build' >> .husky/pre-commit
    chmod +x .husky/pre-commit
    git config core.hooksPath .husky
fi

Make the above bash script executable and just run the above script after the husky install. This will setup a pre-commit hook where build will be executed before each commit. You can make use of any other command that need to be run before performing the commit.


What are some of the npm lifecycle scripts?

Lifecycle Scripts

Some of the key npm lifecycle scripts are:

prepare:

prepublishOnly:

prepack:

postpack:

preinstall:

postinstall:

preuninstall:

postuninstall:

preversion:

postversion:

Some other notable lifecycle scripts includeprepublish(deprecated),prepublishOnly,prepack, andpostpack.