Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 为任何本地依赖项运行postinstall钩子_Node.js_Npm - Fatal编程技术网

Node.js 为任何本地依赖项运行postinstall钩子

Node.js 为任何本地依赖项运行postinstall钩子,node.js,npm,Node.js,Npm,如果我们有: { "scripts":{ "postinstall":"./scripts/postinstall.sh" } } 然后,每当我们执行 $npm安装 在命令行 然而,我想知道的是,当我们安装这样的依赖项时,是否有一种方法可以运行postinstall钩子 $npm安装x 是否有一些NPM钩子可供我们使用?简短回答我知道NPM没有内置的功能提供这种钩子 可能的解决方案,尽管是bash解决方案,但将是使用您自己的自定义逻辑完全覆盖npm install x命令。例

如果我们有:

{
  "scripts":{
    "postinstall":"./scripts/postinstall.sh"
  }
}
然后,每当我们执行

$npm安装

在命令行

然而,我想知道的是,当我们安装这样的依赖项时,是否有一种方法可以运行postinstall钩子

$npm安装x


是否有一些NPM钩子可供我们使用?

简短回答我知道NPM没有内置的功能提供这种钩子


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

  • 创建一个
    .sh
    脚本,如下所示。让我们命名文件
    custom npm install.sh

    #/usr/bin/env bash
    npm(){
    如果[$*==“安装”*|$*==“i”*];则
    #在运行“$npm安装”时(即,“$npm安装…”之后
    #通过一个空格字符和一些其他字符,如包名-运行
    #提供的命令。
    命令npm“$@”
    #然后运行伪“postinstall”命令,例如另一个shell脚本。
    命令路径/to/postinstall.sh
    其他的
    #按常规运行“$npm install”命令和所有其他命令。
    命令npm“$@”
    fi
    }
    
  • 将以下代码段添加到您的
    .bash\u配置文件
    文件中(注意:您需要定义自定义npm安装.sh的实际路径):

    #“npm安装”或
    #运行与“npm i”相同的速记命令。
    .path/to/custom-npm-install.sh
    

  • 注释

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

  • 现在,无论何时运行
    npm install
    或许多其他变体,例如:

    • npm安装@
    • npm安装--保存开发文件
    • npm i-D
    • 等等,等等
    custom npm install.sh
    将按照正常方式运行命令,然后运行命令
    /scripts/postinstall.sh
    (即,无论随后给出的命令设置为什么)

  • 所有其他npm命令将正常运行,例如
    npm安装

  • 给定
    custom npm install.sh
    当前逻辑,只要通过CLI输入
    npm install…
    ,就会运行
    /scripts/postinstall.sh
    。但是,如果您希望它仅在安装特定软件包时运行,则需要更改
    if
    语句中的条件逻辑。例如如果希望仅在安装时运行
    /scripts/postinstall.sh
    ,请将
    if
    语句更改为:

    if[[$*==“install”*“shelljs”*|$*==“i”*“shelljs”*];
    

  • 谢谢,是的,这不仅仅是我自己用的,这是一个库…所以我希望我能给用户一个即插即用的解决方案,他们只需在package.json脚本中添加一个钩子…嗯,绝对没有即插即用的解决方案。这样一个功能tho的用例是什么?(我的好奇心让我发狂!)我有一个非常棒的项目:通常,它对所有项目都运行
    npm link
    。但是在这样做之后,如果在项目中运行
    npm install x
    ,它通常会断开符号链接。因此我需要一种方法在安装后重新对项目进行符号链接。因此,在
    npm install x的安装后脚本中会发生重新符号链接
    。我有很多人使用Lerna而不是
    npm链接
    ,但我实际上认为
    nlu
    要优越得多-Lerna是由巴贝尔团队创建的,因此获得了更多的曝光。