Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.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 如何从全局包运行npm脚本?_Node.js_Npm - Fatal编程技术网

Node.js 如何从全局包运行npm脚本?

Node.js 如何从全局包运行npm脚本?,node.js,npm,Node.js,Npm,比如说,我正在制作一个npm包 示例package.json: { "bin": { "cli": "cli.js" }, "scripts": { "sample": "node sample.js" } } 示例cli.js: const shell = require('shelljs') shell.exec('npm run sample') 然后,我运行npm链接 现在,如果我从项目存储库以外的任何地方运行cli,它将不会运行。相反,它抛出了一个错

比如说,我正在制作一个npm包

示例package.json:

{
   "bin": { "cli": "cli.js" },
   "scripts": { 
    "sample": "node sample.js" 
   } 
}
示例cli.js:

const shell = require('shelljs')
shell.exec('npm run sample')
然后,我运行
npm链接

现在,如果我从项目存储库以外的任何地方运行
cli
,它将不会运行。相反,它抛出了一个错误

通过将cli.js更改为:

const shell = require('shelljs')
, package_path = require('./path.json') 
// I manually created this path.json containing the absolute path of the package

shell.exec('npm run --prefix ${package_path} sample')
这类工作。但主要限制是:

  • 克隆repo后,项目的所有参与者都必须手动设置此路径

  • 如果像
    npm i-g package
    一样全局安装包,那么这种路径更改对用户来说很烦人

我想问的是:

  • 如何自动设置路径

  • 实现相同行为的任何其他更好的方法,即, 从全局
    cli
    脚本调用
    npm脚本


我找到了解决我问题的优雅的解决方案

cli.js
文件编辑为:

const shell = require('shelljs')
shell.exec(`npm run --prefix ${__dirname} sample`)
Node提供了一些facade globals(),这非常有用

在这里,
\uu dirname
是完美的解决方案。它提供执行脚本的路径

希望这对其他开发者有所帮助