I'd like to install a pre-commit
git hook (that lints the code) when someone installs my-package
.
I tried to add a postinstall
script:
"scripts": {
"postinstall": "./scripts/install-git-hooks"
}
This works great. When someone runs npm install
, they get the pre-commit
hook installed.
However, if another-package
depends on my-package
, running npm install
for another-package
runs the postinstall
script as well, which is undesired.
What's the cleanest way to avoid this undesired affect?
npm install git doesn't install git (i.e. the command line tool to manipulate git repositories). It installs the npm package called git which seems to be a JavaScript library to interact with git repositories (which makes the name accurate, but still misleading). npm is not a general-purpose package manager.
To install the hook, you can either create a symlink to it in . git/hooks , or you can simply copy and paste it into the . git/hooks directory whenever the hook is updated. As an alternative, Git also provides a Template Directory mechanism that makes it easier to install hooks automatically.
There is no difference, since "npm i" is an alias for "npm install". They both do the exact same thing (install or update all the dependencies in your package-lock.
You can use the ghooks npm module and add it as a dev-dependency. You can configure what to run before commit in your package.json like so:
[...]
"config": {
"ghooks": {
"pre-commit": "npm test"
}
}
[...]
Hacky, but might work for you.
The trick is to identify (within the script) if it is a sub-dependency or a root dependency for the NPM installation. Simply check if ../../package.json
exists. If so, it's a sub dependency and you should skip installing the hooks.
It should be noted that you are breaking any consistent installation rules, which is exactly against the spirit of the installation scripts. This is to install client-side hooks which cannot be trusted by any means, if you need the linting to be enforced, this should be done server side, where it can just reject code that doesn't comply.
Potentially this issue would be better solved like you mentioned, by having it as a custom install script, and just dealing with the additional communication overhead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With