npm install if package.json was modified

后端 未结 3 1555
再見小時候
再見小時候 2020-12-24 12:39

TL;DR: Is there a way to have npm install run automatically before running any npm script if your package.json has been modified?

Problem

3条回答
  •  甜味超标
    2020-12-24 13:33

    You can create a custom script that will run your smart install.

    smart-install.sh file

    #!/usr/bin/env bash
    
    changedFiles="$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)"
    
    checkForChangedFiles() {
        echo "$changedFiles" | grep --quiet "$1" && eval "$2"
    }
    
    packageJsonHasChanged() {
      echo "Changes to package.json detected, installing updates"
      npm i
    }
    
    checkForChangedFiles package.json packageJsonHasChanged
    

    Then if you have husky you can add that to the post-checkout hook or any hook you like. If you don't have husky, you can also add it directly to the scripts which essentially do the same thing.

    .huskyrc file

    {
      "hooks": {
        "post-checkout": "npm run smart-install"
      }
    }
    

    package.json file

    "scripts": {
      ...
      "smart-install": "bash ./bin/smart-install.sh",
    }
    

    Either way it's a good idea to create a npm script to run smart-install

提交回复
热议问题