Say, I am making a npm package.
sample package.json:
{
"bin": { "cli": "cli.js" },
"scripts": {
"sample": "node sample.js"
}
}
sample cli.js:
const shell = require('shelljs')
shell.exec('npm run sample')
Then, I run npm link
Now, if I run cli from anywhere, other than the project repository, it does not run. Instead, it throws an error.
I found a workaround by changing cli.js as:
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')
This sort of works. But main limitations are:
all contributors of the project must manually set this path after cloning the repo.
if the package is globally installed like
npm i -g packagethen this path changing is annoying for the user.
What I'm asking is:
How can I automate setting the path?
Any other better way to achieve the same behavior, that is, calling a
npm scriptfrom a globalcliscript?