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"
},
}
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’ "
},
}
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
.
Top comments (0)