Interpolation feature for npm script commands


(Alex Kit) #1

A quite useful feature would be the interpolation support for npm script commands, so that we can pass parameters from env or cli when running commands.

"foo": "git commit -am ${argv.message} && git push origin ${env.BRANCH} && npm run success-hook"

The example script contains of 3 commands, 2 of them have the interpolations - one from additional CLI param, and another one from the env.

$ npm run foo --message "Lorem ipsum"

What do you think, would it useful? Or is there some other cross-platform way to achieve the arguments injections I’m not aware of?


(Lars Willighagen) #2

The environment variable should be possible to access as $BRANCH (although that may be different on Windows). Also, you can append arguments with --. For example, with

  "test": "mocha -R dot test/**/*.spec.js"

you can run

npm test -- -R spec --grep="feature"

to add extra options. However, that doesn’t apply in your git commit -m case.


Appending arguments also helps with lerna. I can create a lerna scripts:

This can be called as

npm run lerna -- npm test

or

npm run lerna -- npm outdated

to run a command in each or a specific number of lerna packages.


(Alex Kit) #3

On Windows it is %BRANCH%. I known, appending now works, but this doesn’t work when multiple commands with && are used and we want to pass arguments for a command other then the last one.

So once again the requirements:

  1. Cross-Platform
  2. No 3rd party dependencies. (Sure, any problem can be solved with other runners, tools and scripts)
  3. Pass arguments anywhere in a command, not just appending.

(Nathaniel Palmer) #4

This would also be useful for providing user-local config for tools that don’t support it directly.


(John Gee) #5

It would be useful, and I looked for it too, but I think hard to add to existing npm run <script> without breaking existing scripting.

A package solving a related but different problem is: https://www.npmjs.com/package/cross-env

The approach I take is when the scripting needs more configuration than npm run <script> can provide, time to move the logic into a separate file! (Still with an entry in scripts.) For cross-platform I use TypeScript to implement the script and been pleased with how it has worked out for setting up cross-platform workflows.