How to pass argument to your node script

hermannleboss

EHO Koku Hermann

Posted on October 4, 2022

How to pass argument to your node script

Sometimes you need to pass arguments to your node script so they can be more dynamic. Let's see how to do that.
Let imagine you have a node project with script part like that

{
 "scripts": {
    "example": "echo 'hello world'",
    "webpack": "webpack serve"
  },
}
Enter fullscreen mode Exit fullscreen mode

You can run
npm run example
The you will have hello world as result
Or npm run webpack
then you have a webpack server who starts running.
Now if we want to pass arg when executing the CLI command, you can do that.

{
 "scripts": {
    "example": "echo \"Hello world, i'm $npm_config_first npm_config_last\" ",
    "webpack": "webpack serve --first=’Amah’ --second=’Kwatcha’ "
  },
}
Enter fullscreen mode Exit fullscreen mode

Then run:
npm run example --last=Amah --first=Kwatcha
or npm run webpack.
With the first one you will get Hello world, i'm Kwatcha Amah
Then in your project when we run the webpack script, you can access the arguments in your environment variables.
process.env.npm_config_[args_name]
here in process.env.npm_config_first & process.env.npm_config_last.

💖 💪 🙅 🚩
hermannleboss
EHO Koku Hermann

Posted on October 4, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related