javascriptnode.jsnpmlifecycle

Is there a way to run a node dependency's postinstall script on install?


I'm trying to run my postinstall script every time someone runs npm install within their project where they have my package installed as a dependency.

Here's a minimal example of what my package's package.json looks like:

{
  "name": "example",
  "version": "0.0.0",
  "scripts": {
    "postinstall": "node -e \"try{require('./scripty')}catch(e){}\""
  }
}

For sake of verbosity, here's what scripty.js looks like:

console.log('im a script');

Here's a minimal example of what someone's package.json would look like:

{
  "name": "parent",
  "version": "0.0.0",
  "dependencies": {
    "example": "0.0.0"
  }
}

What I'm expecting to see is when the parent project runs npm install, in addition to installing all their dependencies, they will also see

im a script

logged in their terminal as a result of my example package's postinstall script.

As it stands, I'm not seeing anything on install. What am I missing?

Minimal repro/playground for the issue: https://stackblitz.com/edit/stackblitz-starters-czrx3p?file=testy%2Fscripty.js


Solution

  • postinstall scripts may not run in Stackblitz due to their usage of Turbo, as per their documentation:

    Turbo does not run install scripts for your dependencies. This increases the security of the installation process, and prevents the spurious errors arising from the differences between the underlying platform (WebContainers) and a local environment.

    Otherwise locally, the postinstall script should be running and you can check this by running npm install --loglevel=verbose or npm install --foreground-scripts. What you may be encountering is that npm prevents dependencies logging messages to the console, see issue #3647 in the npm/cli GitHub repository for details.