Published 13/06/2016
Nifty: How to pass parameters into npm script (Eg. webpack start)

How to pass parameters into npm script

NodeJS

Imagine that we have npm, or yarn as our build tool for JavaScript.

We can define npm scripts like start, build, test in package.json.

For example:

{
   "scripts": {
       "start": "webpack-dev-server ..."
   }
}

What if we want to run npm start with parameters eg. --server=localhost. By simply running npm start --server=localhost this passes variable to npm, but it's being ignored in script defined inside package.json:

"start": "webpack-dev-server --content-base=public/ --inline --hot ((WE WANT ALSO --server=localhost HERE))"

There are (at least) 2 options how to solve this.

  1. We can define environment property in command line like: server=localhost npm start

    • Then we are able to ready that property: process.env.server
    • Note: For cross platform compatibility (for Win) use cross-env dependency
  2. We can use special npm command -- and pass parameters directly into all running scripts. Like this: npm start -- --server=localhost

    • We can output parameters with: console.log('process.argv', process.argv);

Second option may be better as we do not need to introduce environment variable, but instead we just pass required parameters directly into scripts.

Yarn differences

Note that when using yarn as your dependencies manager. You can directly specify parameters without extra --.

With yarn v1, you will get this warning:

warning From Yarn 1.0 onwards, scripts don't require "--" for options to be forwarded. In a future version, any explicit "--" will be forwarded as-is to the scripts. 

References

Official docs: https://docs.npmjs.com/cli/run-script