1
0

huskyのv8とv9の違いを確認しつつ、npm scriptsを理解する

Posted at

概要

husky がずっとv4のプロジェクトがあるので、 Node.js のバージョンアップに合わせてアップデートをしようとしました。
2024/1/25にv9.0.1がリリースされていたので違いを確認しつつ、 npm について理解したことをまとめます。

v8とv9の違い

Release Note

v9に変わり、インストール時のコマンドが一つで済むようになり、 .husky/pre-commit もシンプルになっています。

例えば、v8のインストール手順のコマンドは以下です。

npm pkg set scripts.prepare="husky install"
npm run prepare
npx husky add .husky/pre-commit "npm test"

v9では上記のコマンドは以下で全て実行されます

npx husky init

他には、v9にあたり Node.js のv14とv16のサポートが外れ、v18以上の engines の指定が追加されています。

npm について

npm-pkg

package.json の読み書きができます.

example
npm pkg set version=1.0.1
npm pkg get version
# 1.0.1

つまり、huskyの最初のコマンドは scripts に prepare として husky install を設定しています

npm pkg set scripts.prepare="husky install"

npm-scripts

公式のサンプルですが、基本的な考え方として Pre/Post の接頭辞を定義することで、 scripts の実行前後に処理を実行することができます

公式サンプル
{
  "scripts": {
    "precompress": "{{ executes BEFORE the `compress` script }}",
    "compress": "{{ run command to compress files }}",
    "postcompress": "{{ executes AFTER `compress` script }}"
  }
}

これとは別に特別なライフサイクルイベントとして、いくつか他の scripts が存在し、 prepare はその一つです。
preapare が組み込まれている scripts は以下です。実行順序は公式ドキュメントを確認してください

  • npm cache add
  • npm ci
  • npm diff
  • npm install
  • npm pack
  • npm publish
  • npm rebuild

インストール時や成果物生成の時に常に実行される scripts のようです
このため、複数人で開発する時にきちんと git-hooks の設定がおこなわれることになります

サンプルコード

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0