Skip to content

Docs suggestion: use "prepare" instead of "postinstall" #884

@nathansmith

Description

@nathansmith

TL;DR = Suggestion for the documentation site

This is not a bug "issue," but I wanted to make a suggestion for the docs.

I think this could alleviate some confusion around postinstall and remove the necessity for pinst entirely.

Currently, the Husky v5 documentation reads like this.

To automatically have Git hooks enabled after install, edit package.json

// package.json
{
  "private": true,
  "scripts": {
    "postinstall": "husky install"
  }
}

Instead, that could be changed to this. Swap out posinstall for prepare.

Also, private does not matter because prepare runs the same regardless.

To automatically have Git hooks enabled after install, edit package.json

// package.json
{
  "scripts": {
    "prepare": "husky install"
  }
}

Longer explanation

I did a writeup for my coworkers, to explain our automated setup for configuring Husky v5.

Basically, this all runs via NPM with the prepare command and puts everything into place.

If this is helpful for the docs, feel free to repurpose it.

This prepare.js file runs after npm install, when pulling down dependencies.

{
  "scripts": {
    "prepare": "node ./scripts/prepare.js"
  }
}

Unlike postinstall, the prepare command does not run when a NPM package is installed as a dependency in another project.

Meaning, it will not run within a package when someone types this…

npm install your-npm-package

…to install it for their own project.

But it will run when working on your-npm-package and installing other dependencies locally. This replicates the behavior we had before with Husky v4.

Code within the prepare.js file looks like this.

// =======
// Import.
// =======

const { execSync } = require('child_process');
const { existsSync } = require('fs');

// ===========
// File paths.
// ===========

const FILE_COMMIT = './.husky/pre-commit';
const FILE_HUSKY = './.husky/_/husky.sh';

// =========
// Commands.
// =========

const CLI_COMMIT = 'npx husky add .husky/pre-commit "npx lint-staged"';
const CLI_HUSKY = 'npx husky install';

// ==============
// Husky install.
// ==============

if (!existsSync(FILE_HUSKY)) {
  global.console.log(CLI_HUSKY);
  execSync(CLI_HUSKY);
}

// ====================
// Add pre-commit hook.
// ====================

if (!existsSync(FILE_COMMIT)) {
  global.console.log(CLI_COMMIT);
  execSync(CLI_COMMIT);
}

Code within the conditional logic will create .husky/pre-commit if it does not yet exist.

That adds a snippet (instructions for Husky) at the top of the file, and then appends the actual text that we passed in.

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx lint-staged

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions