npm install if package.json was modified

后端 未结 3 1563
再見小時候
再見小時候 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:31

    Like other answers, but I think simpler because it's one line of shell script in package.json:

    {
        "scripts": {
            "install-if-needed": "[ package.json -nt node_modules ] && npm install && touch node_modules",
            "my-script": "npm run install-if-needed && ..."
        }
    }
    

    or, basically equivalent:

    {
        "scripts": {
            "install-if-needed": "[ package.json -nt node_modules ] && npm install && touch node_modules",
            "premy-script": "npm run install-if-needed",
            "my-script": "..."
        }
    }
    

    You'll have to either inline npm run install-if-needed or have a pre... script for each script that needs it -- I don't know any other way to have it run before multiple other scripts.

    Explanation: install-if-needed checks the modification times on package.json and node_modules. If node_modules is newer, it does nothing; otherwise it runs npm install. The final touch node_modules is necessary because npm install may itself change the package.json modification time (if it is correcting whitespace in package.json for example).

提交回复
热议问题