Member-only story
Scripting inside package.json
Package.json has various sections, scripts is one of them, which allows you to write npm script which we can run using npm run <script-name>.
Run npm run
to see available scripts. Binaries of locally install packages are made available in the PATH
, so you can run them by name instead of pointing to node_modules/.bin/name
.
Typically we can have a scripts section, where we define json like key value script , Where Key is the command name which we will use to run and value is the command we want to run. A Example package.json is given below.
"scripts": {
"build": "react-scripts build",
"code:check": "yarn code:lint && yarn code:format --check",
"validate": "run-p --print-label lint typecheck test build",
"preversion": "git pull",
"postversion": "git push && git push --tags"
},
so to run the build we have to do
npm run build
and it will execute react-scripts build script. which in-turn build our code.
Options for npm scripts
Passing options to used commands
You can pass options to the command you are using in your npm script by adding -- --flag
like in the example below.
{
"name": "my-package",
"scripts": {
"lint": "xo",
"lint:fix": "npm run lint -- --fix",
}
}
Adding the -- --fix
option is like executing xo --fix
. as lint:fix calling lint.
Calling Shell and Node Scripts
Sometime we have to call any shell scripts , which can be called using node script.
Let’s quickly write a bash script that says hello to you. Create a file called hello.sh
in your root directory and paste this code in it:
#!/usr/bin/env bash# filename: hello.shecho "What's your name?"read nameecho "Hello there, $name!"
It’s a simple script that echoes your name back to you. Now modify the package.json
file so that the scripts
object has this line of code:
"bash-hello": "bash hello.sh"
Now, when you run npm run bash-hello
, it asks you for your name and then says hello to you!
You can do the same thing with JS scripts run using node. An advantage of this approach is that this script will be platform independent since it…