如何在单独执行“npm install <package"后运行安装后脚本? [英] How to run a post-install script after individual execution of &quot;npm install &lt;package&gt;&quot;

查看:45
本文介绍了如何在单独执行“npm install <package"后运行安装后脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在维护以下目录结构:

I am maintaining the following directory structure:

/home/user/Desktop/
                 |-- app/
                 |      |-- package.json
                 |      `-- server.js
                 |-- node/
                 |      |-- bin/
                 |      |      |-- node
                 |      |      `-- npm
                 |      |-- include/
                 |      |-- lib/
                 |      `-- share/
                 |
                 `-- npm.sh

我希望我本地安装的所有节点模块都位于 node 目录中.也就是说,如果我在 app 目录中运行 npm install,最初它会在当前目录 (app) 中安装模块,然后将 node_modules 文件夹移动到名为 node 的外部目录.为此,我编写了一个脚本 npm.sh 并将 mv(移动)命令放在 package 的 postinstall 脚本中.json.

I want all my locally installed node modules reside in the directory node. That is, if I run npm install inside the directory app, initially it'll install the modules inside the current directory (app) and then move the node_modules folder to the external directory called node. For this purpose I've written a script npm.sh and placed the mv (move) command inside the postinstall script of package.json.

这些是文件 npm.shpackage.json.

npm.sh 的内容:

content of npm.sh:

#/bin/bash

export PATH=/home/user/Desktop/node/bin:$PATH
export NODE_PATH=/home/user/Desktop/node/node_modules
export NODE_MODULE_ROOT=/home/user/Desktop/node
/bin/bash

app/package.json 的内容:

content of app/package.json:

{
  "name": "app",
  "version": "1.0.0",
  "scripts": {
    "postinstall": "mv node_modules $NODE_MODULE_ROOT",
    "start": "node server.js"
  },
  "dependencies": {
    "jwt-simple": "^0.5.1"
  }
}

但问题是:当我执行 ./npm.sh &&cd app &&npm install,一切都按预期工作.但是当我执行 npm install jwt-simple 时,postinstall 脚本没有被执行.

But the problem is: when I do ./npm.sh && cd app && npm install, everything works as intended. But when I do npm install jwt-simple, the postinstall script is not getting executed.

有没有办法让它适用于单个 npm install ?或者有没有更好的方法来实现这一点?

Is there a way to make it work for individual npm install <package> ? Or is there any better way to accomplish this ?

推荐答案

您可以使用 npm 钩子脚本在安装包后做一些事情.

You can use npm hook scripts to do something after package is installed.

创建 node_modules/.hooks/postinstall 可执行文件,它也会在 npm install 之后运行.

Create node_modules/.hooks/postinstall executable and it will be run also after npm install <package>.

注意: 我注意到 npm 版本 5.1.0 到 6.0.1 之间的 npm 钩子脚本存在问题.因此,如果您遇到 hooks 问题,请检查您的 npm 版本并在必要时升级.

NOTE: I have noticed problems with npm hook scripts between npm version 5.1.0 until 6.0.1. So if you have problems with hooks, check your npm version and upgrade if necessary.

这篇关于如何在单独执行“npm install <package"后运行安装后脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆