Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run npm scripts from global packages?

Tags:

node.js

npm

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?

like image 464
kalpa Avatar asked Oct 18 '22 08:10

kalpa


1 Answers

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.

like image 92
kalpa Avatar answered Nov 01 '22 13:11

kalpa