However, sometimes you want to be able to pass arguments to your scripts so they are more dynamic. There are two different ways to pass arguments to npm scripts. The first method simply passes the arguments directly to your actual command. For example: Bash Copy the code npm run build -- --watch Will be executed as follows: Bash Copy the code tsc --watch What's important here is that it is -- followed by a space. Anything that appears after it is passed one at a time into the actual script command. This is useful in situations like the example shown above where you are exposing a basic command as tsc and when you occasionally want to pass additional arguments to the command.
The second option is to use npm's built-in argument parser. This telegram philippines girl is probably one of the lesser-known features of npm scripts but I was super excited when I discovered it. Essentially, npm parses all the arguments you pass to the script unless they are passed after the code -- followed by a space. Once npm parses them, they are available as npm_config_ environment variables. To test this, create a new entry scripts : Json Copy the code { "scripts": { "demo": "echo \"Hello $npm_config_first $npm_config_last\"" } } Run: Bash Copy the code npm run demo --last=Kundel --first=Dominik The output should be Hello Dominik Kundel.
It is important to note that since we are not configuring this argument parser, it is not very flexible regarding argument syntax. For example, if we remove the signs = and rerun the same command: Bash Copy the code npm run demo --last Kundel --first Dominik We get Hello true true Kundel Dominik, because it will consider --last and --first as boolean flags, set their value to true , and pass the rest of the arguments to the script as unparsed arguments, resulting in the call of echo "Hello $npm_config_first $npm_config_last" "Kundel" "Dominik". However, even though the argument parser is relatively strict, it is a very powerful tool if you plan to create some simple scripts without dealing with argument parsing.
The second option is to use
-
- Posts: 9
- Joined: Sun Dec 22, 2024 5:29 am