Node.js 如何从全局包运行npm脚本?
比如说,我正在制作一个npm包 示例package.json: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,它将不会运行。相反,它抛出了一个错
{
"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
是完美的解决方案。它提供执行脚本的路径
希望这对其他开发者有所帮助