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 package
then 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 script
from a global cli
script?
I found the elegant solution to my problems.
Edit the cli.js
file as:
const shell = require('shelljs')
shell.exec(`npm run --prefix ${__dirname} sample`)
Node provides some facade globals (read here) which are really helpful.
Here, __dirname
is the perfect solution. It provides the path of the executing script.
Hope this helps any other developers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With