TeamCity: NPM Install When Changes To Package.json

You all should know by now that npm install is something that takes a fair bit of time to run, some would actually say that it downloads the whole internet. It's a very time consuming process even if there's no changes to package.json at all.

We're using TeamCity in the current project I'm working on and we love it. But one of the things that got me blocked was how to conditionally run a build step. Basically, I only want to run npm install if there's any change at all to package.json otherwise don't bother. This way I'd save at least 4 minutes from my build.

It seems that TeamCity doesn't have any way to conditionally run a build step, apart from whether the previous step failed or not. One alternative was to create two build configurations and modify the trigger by adding +:**package.json for the one that will run npm install and adding -:**package.json for the one that will not.

I wasn't particularly happy with this approach, so I started thinking out of the box and found out that TeamCity provides a file that lists all changed files and it's available in the build step via this variable %system.teamcity.build.changedFiles.file%.

Then I created a new Command Line build step and added this script which will check if the file contains package.json and if does then it will run npm install otherwise not:
find /c "package.json" "%system.teamcity.build.changedFiles.file%" && (npm install) || (echo "PACKAGE.JSON NOT MODIFIED")

Here's the build step:

An extra line I've added after the fact was this one if NOT EXIST node_modules npm i in case the node_modules folder is not there at all and you haven't made any changes to package.json.

Hope it helps.

Cheers.