今日偶得,npm run-script *(或者npm run *)实际上是开启了shell进程,执行命令。
比如对于 “scripts”: {“link”: “eslint .”} ,npm run link 等价于 (node) ./node-modules/.bin/eslint . 。这是为啥呢?
- npm run link == node eslint .
- npm run 会自动在$PATH中添加./node-bodules/.bin 目录,因此 上述命令 == node ./node-modules/.bin/ eslint .
- ./node-modules/.bin/ eslint 这个链接啥时候有的呢? npm i eslint 时候,除了把eslint 安装在node-modules子目录,还会自动在 ./node-modules/.bin 下生成符号链接,指向 eslint的执行脚本
ps直接执行 node ./node-modules/.bin/ eslint . 也可以之所以可以用node** 是因为,脚本有两种执行方式,第一种是直接用路径,然后系统用第一行shebang指定的解释器;第二种是直接指定解释器(node),这样会忽略第一行的shebang。打开./node-modules/.bin/ 下的文件,我发现第一行都是 #! /usr/bin/env node ,( #! 符号的名称叫 Shebang,用于指定脚本的解释程序)。
至于为啥 我还没弄明白,猜是shell执行的时候选择了node解释二进制文件。所以可以省略node
from https://www.cnblogs.com/qinmengjiao123-123/p/8503163.html :
!/usr/bin/node是告诉操作系统执行这个脚本的时候,调用/usr/bin下的node解释器;
!/usr/bin/env node这种用法是为了防止操作系统用户没有将node装在默认的/usr/bin路径里。当系统看到这一行的时候,首先会到env设置里查找node的安装路径,再调用对应路径下的解释器程序完成操作。
!/usr/bin/node相当于写死了node路径;
!/usr/bin/env node会去环境设置寻找node目录,推荐这种写法
那env是啥?env里面有PATH,PATH里面有node
ps :npm 官网: By default, on Unix-like systems it is the /bin/sh command, on Windows it is cmd.exe. The actual shell referred to by /bin/sh also depends on the system.You can customize the shell with the script-shell configuration 默认情况下,类unix 系统,会执行 bin/sh 命令, windows 执行 cmd.exe。 /bin/sh 实际用到的是哪个shell 也取决于系统,可以通过 script-shell 来配置。
ps 无论在哪个目录执行npm run * 脚本都是在根目录执行
ps from阮一峰(https://www.ruanyifeng.com/blog/2016/10/npm_scripts.html): 由于 npm 脚本的唯一要求就是可以在 Shell 执行,因此它不一定是 Node 脚本,任何可执行文件都可以写在里面。