简体   繁体   中英

Is there good way to run a script only when the user install my npm package manually?(not installed by dependency)

I'm under developing my npm package and I want to run a specific script only when user installed my package manually like npm install my-package --save-dev or something npm command.

I'd not like to run the command when the package was installed via package dependency. For example, My package is dependency of the other package other-package . Even if the user installed other-package manually and npm should install my-package as dependency, I'd not like to run the script.

Is there good way to handle this?

npm has a set of scripts that will automatically run when npm is launched a particular way. The scripts you might be interested in are:

  • prepublish : Run BEFORE the package is published. (Also run on local npm install without any arguments.)
  • publish , postpublish : Run AFTER the package is published.
  • preinstall : Run BEFORE the package is installed
  • install , postinstall : Run AFTER the package is installed.

There is no event that exactly matches your criteria but you could use one of the install events and then have an intermediate script that detects the npm command line options before your actual script.

Due to the (imo horrible) way prepublish works, a number of people have written modules to do a similar task and these could easily be adapted to your requirements.

iarna/inpublish is a good example. It check's process.env['npm_config_argv'] for the existence of /^i(n(s(t(a(ll?)?)?)?)?)?$/

Using the following package.json setup:

"scripts": {
  "postinstall": "my-install && install-manual-tasks || not-my-install"
}

If my-install uses process.exit(0) then install-manual-tasks will run. If you process.exit(1) , not-my-install will clean up so the npm task doesn't fail.

I think this setup actually has an issue. If your install-manual-tasks fails, the exit status is silenced and the npm task won't fail but it's a start at least. You could work around this by doing all your checks in the install-manual-tasks script, then you don't need use the shell tricks to run multiple scripts.

You can take a look at https://superuser.com/a/105389/627275 to see how to create a shell function that acts as an alias to a command. This way, npm install would act as an alias to whatever you want to run in reality. It could also be an alias to bash something.sh & npm install .

Hope that answers your question!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM