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

How to pass parameters into npm script


Imagine we have npm as our dependency and build tool for JavaScript.

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

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/ --progress --inline --hot ((WE WANT ALSO --server=localhost HERE))"

There are (at least) 2 options.

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

    • Then we are able to ready that property: process.env.server
  2. We can use special npm command -- and pass parameter directly into all running scripts Example: 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 and just pass required parameters directly into scripts.


Official docs: