How do I add a custom script to my package.json file that runs a javascript file?
Steps are below:
In package.json add:
"bin":{ "script1": "bin/script1.js" }
Create a
bin
folder in the project directory and add filerunScript1.js
with the code:#! /usr/bin/env node var shell = require("shelljs"); shell.exec("node step1script.js");
Run
npm install shelljs
in terminalRun
npm link
in terminalFrom terminal you can now run
script1
which will runnode script1.js
Reference: http://blog.npmjs.org/post/118810260230/building-a-simple-command-line-tool-with-npm
I have created the following, and it's working on my system. Please try this:
package.json:
{
"name": "test app",
"version": "1.0.0",
"scripts": {
"start": "node script1.js"
}
}
script1.js:
console.log('testing')
From your command line run the following command:
npm start
Additional use case
My package.json file has generally the following scripts, which enable me to watch my files for typescript, sass compilations and running a server as well.
"scripts": {
"start": "concurrently \"sass --watch ./style/sass:./style/css\" \"npm run tsc:w\" \"npm run lite\" ",
"tsc": "tsc",
"tsc:w": "tsc -w",
"lite": "lite-server",
"typings": "typings",
"postinstall": "typings install"
}
Custom Scripts
npm run-script <custom_script_name>
or
npm run <custom_script_name>
In your example, you would want to run npm run-script script1
or npm run script1
.
See https://docs.npmjs.com/cli/run-script
Lifecycle Scripts
Node also allows you to run custom scripts for certain lifecycle events, like after npm install
is run. These can be found here.
For example:
"scripts": {
"postinstall": "electron-rebuild",
},
This would run electron-rebuild
after a npm install
command.