【问题标题】:Run postinstall hook for any local dependency为任何本地依赖项运行 postinstall 挂钩
【发布时间】:2018-08-05 15:13:17
【问题描述】:

如果我们有这个:

{
  "scripts":{
    "postinstall":"./scripts/postinstall.sh"
  }
}

然后这个 postinstall 钩子将在我们执行时运行

$ npm install

在命令行

然而,我想知道的是,当我们安装这样的依赖项时,是否有办法运行安装后挂钩

$ npm install x

有没有我们可以使用的 NPM 钩子?

【问题讨论】:

    标签: node.js npm


    【解决方案1】:

    简短回答我知道,npm 没有内置功能可以提供这种钩子。


    可能的解决方案,尽管是一个 bash 解决方案,但将使用您自己的自定义逻辑完全覆盖 npm install x 命令。例如:

    1. 如下创建.sh 脚本。让我们将文件命名为custom-npm-install.sh

      #!/usr/bin/env bash
      
      npm() {
        if [[ $* == "install "* || $* == "i "* ]]; then
      
          # When running `$ npm install <name>` (i.e. `$ npm install ...` followed
          # by a space char and some other chars such as a package name - run
          # the command provided.
          command npm "$@"
      
          # Then run a pseudo `postinstall` command, such as another shell script.
          command path/to/postinstall.sh
        else
          # Run the `$ npm install` command and all others as per normal.
          command npm "$@"
        fi
      }
      
    2. 将以下 sn-p 添加到您的 .bash_profile 文件中(注意:您需要定义到 custom-npm-install.sh 的实际路径)

      # Custom logic applied when the `npm install <name>` or the
      # shorthand equivalent `npm i <name>` command is run.
      . path/to/custom-npm-install.sh
      

    备注

    1. 按照上述第二点配置您的.bash_proile 后,您需要创建一个新的终端会话/窗口以使其生效。该逻辑将在此后的所有终端会话中生效。

    2. 现在,无论何时运行 npm install &lt;name&gt; 或许多其他变体,例如:

      • npm install &lt;name&gt;@&lt;version&gt;
      • npm install &lt;name&gt; &lt;name&gt; --save-dev
      • npm i -D &lt;name&gt;
      • 等等等等……

      custom-npm-install.sh 将照常运行命令,然后运行命令./scripts/postinstall.sh(即,随后给定的命令设置为什么)。

    3. 所有其他 npm 命令将正常运行,例如npm install

    4. 给定custom-npm-install.sh 当前逻辑,只要通过 CLI 输入npm install &lt;name&gt; ..../scripts/postinstall.sh 就会运行。但是,如果您希望它在安装特定软件包时运行ONLY,那么您需要更改if 语句中的条件逻辑。例如,如果您希望./scripts/postinstall.sh 在安装shelljs 时运行ONLY,则将if 语句更改为:

      if [[ $* == "install "*" shelljs"* || $* == "i "*" shelljs"* ]];
      

    【讨论】:

    • 谢谢,是的,这不只是供我自己使用,它是一个库..所以我希望我可以给用户一个即插即用的解决方案,他们只需添加一个钩子到package.json 脚本...嗯
    • 绝对没有即插即用的解决方案。这种功能的用例是什么? (我的好奇心快要死了!)
    • 我有一个非常棒的项目:github.com/ORESoftware/npm-link-up
    • 通常,它为所有项目运行npm link。但是在这样做之后,如果您在项目中运行npm install x,它通常会破坏符号链接。所以我需要一种在安装后重新符号链接项目的方法。所以重新符号链接会在 npm install x 的安装后脚本中发生。
    • 我很多人用 Lerna 代替了npm-link-up,但我实际上认为nlu 更胜一筹——Lerna 是 Babel 团队创建的,因此获得了更多曝光。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 2015-04-09
    • 2021-03-03
    相关资源
    最近更新 更多