Published 2016-6-13
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.

References

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