How do I run an npm script of a dependent package

2019-04-19 18:57发布

I have a package that itself has a script in its package.json that I would like to be able to run in my top-level project. This package is one of my top-level projects dependencies. I'm looking for a way to directly or indirectly call the dependency packages script.

Let us assume the module name I'm working with is named foo and the script I want to run is updateFooData.

I tried using the syntax npm run-script <package> <...> to run it, but this appears to be deprecated functionality as I can't find it in the current official documentation but I see it in other (very old) search results.

npm run-script foo updateFooData

# npm ERR! missing script: foo

I also looked into the npm api and while npm.commands.run-script(args, callback) will do what I want, I can't figure out how to load the module into npm

{
  ...
  "scripts":{
    "foo:updateFooData": "node --eval \"... ??; npm.commands.run-script('updateFooData', callback)\""
  }
}

npm run foo:updateFooData
# Obviously fails

The only thing I've found that works so far is to CD into the submodule directory and run npm from there. This is not the preferred solution for me.

cd node_modules/foo
npm run updateFooData

标签: npm
2条回答
beautiful°
2楼-- · 2019-04-19 19:05

Note:

This isn't a very good idea. You have no guarantee which node_modules folder module will be installed in as NPM will attempt to optimise space by installing shared packages at the highest level possible. – @superluminary


Something I've found that does work:

If the script you are running runs a script file, you can look at the path of the file it's running and run the script using a require:

# if node_modules/foo/package.json looks like this
{
  "scripts": {
    "updateFooData":"scripts/updateFooData.js"
  }
}

# then package.json can look like this
{
  "scripts": {
    "foo:updateFooData":"node --eval \"require('foo/scripts/updateFooData.js')\""
  }
}

# or package.json can look like this
{
  "scripts": {
    "foo:updateFooData":"node node_modules/foo/scripts/updateFooData.js"
  }
}

# and you can run it like this
npm run foo:updateFooData

I don't like this solution because it only works if the npm script you are running is a file. It won't apply in all

查看更多
神经病院院长
3楼-- · 2019-04-19 19:16

I ran into this trying to run the updatedb script for geoip-lite. You should use the npm explore command which will spawn a new shell in a dependencies' directory.

So for your use case, try npm explore foo -- npm run updateFooData

查看更多
登录 后发表回答