TIL: Run scripts after npm install with postinstall

May 25, 2017JavaScriptNPM

The other day when I was upgrading React Native I ran into this issue here. Basically, there was a naming collision between files in the fbjs dependency which was scattered throughout a few different dependencies I had in my project.

I quickly found I could resolve this issue by installing fbjs as one of my own dependencies and then going through and removing all the other instances so at runtime the code would reference the top level insance of fbjs. However, after doing this twice manually I decided this needed to be automated. I'm kind of lazy... in a good way...

This is when I found out about postinstall scripts in NPM. The npm documentation site says that postinstall will "run AFTER the package is installed." Now, I'm not sure if this was intended for just modules that you release on NPM for others to use, but it also works in your own project. Here's a sample from my package.json file with the postinstall script to remove all other versions of fbjs.

{
  ...
  "scripts": {
    ...
    "postinstall": "find . -name 'fbjs' -print | grep \"\\./node_modules/fbjs\" -v | xargs rm -rf",
    ...
  },
  ...
}

That's it! You can easily define scripts to run right after every npm install. Who knew?

The author, Jason Merino, with sun glasses and a hat

Jason Merino 💻 🚀

Software engineer, TypeScript enthusiast, avid gardener, all around family man, Franciscan at heart, celiac, aphantasiac. I enjoy nature and a good technical manual.

Follow me on Twitter and checkout my code on Github!