简体   繁体   English

如何在“npm install”上安装git hooks?

[英]How to install git hooks on “npm install”?

I'd like to install a pre-commit git hook (that lints the code) when someone installs my-package . 当有人安装my-package时,我想安装一个pre-commit git hook(它会破坏代码)。

I tried to add a postinstall script: 我试图添加一个postinstall脚本:

"scripts": {
  "postinstall": "./scripts/install-git-hooks"
}

This works great. 这非常有效。 When someone runs npm install , they get the pre-commit hook installed. 当有人运行npm install ,他们会npm install pre-commit挂钩。

However, if another-package depends on my-package , running npm install for another-package runs the postinstall script as well, which is undesired. 但是,如果another-package依赖于my-package ,则为another-package运行npm install也会运行postinstall脚本,这是不希望的。

What's the cleanest way to avoid this undesired affect? 什么是避免这种不良影响的最简洁方法?

You can use the ghooks npm module and add it as a dev-dependency. 您可以使用ghooks npm模块并将其添加为dev-dependency。 You can configure what to run before commit in your package.json like so: 您可以在package.json中配置提交之前运行的内容,如下所示:

[...]
"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. 诀窍是识别(在脚本中)它是否是NPM安装的子依赖项或根依赖项。 Simply check if ../../package.json exists. 只需检查../../package.json存在。 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. 这是为了安装客户端钩子,如果你需要强制执行linted,那么这个钩子是不可信任的,这应该在服务器端完成,它可以拒绝不符合的代码。

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. 可能这个问题会像你提到的那样更好地解决,将它作为自定义安装脚本,并且只处理额外的通信开销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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