Author: Stefano Frasca
Well. As the title says, let’s talk about a script: scripts that run in the NPM ecosystem.
In a developer’s work path it is very common to find yourself repeating tasks like deleting temporary files, minify and bundling your Javascript source code, preprocessing Sass files, and so on.
NPM scripts are now widely used to handle these repetitive tasks, compared to bash scripts or task managers like Grunt or Gulp because of:
- their ease of use
- the wide adoption of the Node / NPM ecosystem
- no additional CLI or plugin required to execute
Structure and Use
The NPM scripts are defined within the “scripts” object of the package.json file.
A JSON-based structure is used with ‘key: value’ pairs where the key is the name of the script and the value is the command to be launched.
We define a custom script ‘clean-project’ inside the package.json (created with npm init, usually in the root folder of the project)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
{ "name": "awesome-package", "version": "0.0.1", "scripts": { "clean-project": "rm -rf dist/js/* && rm -rf dist/css/*" }, "dependencies": { ... } "devDependencies": { ... } } |
Calling
1 |
npm run clean-project |
the contents inside folder dist/js and dist/css will be deleted.
This is a basic example of how to invoke an NPM Script: it’s possible to combine many NPM simple custom scripts to perform complex tasks as project build/deploy.
Assume, for example, to have webpack as bundler (this is what we use in Madisoft). A more complex (but only for testing purpose) deploy script could be
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
{ "name": "awesome-package", "version": "0.0.1", "scripts": { "clean-project": "rm -rf dist/js/* && rm -rf dist/css/*", "build": "npm run clean-project && webpack --config=webpack.config.js --mode production --progress --display-depth --optimize-minimize" "deploy": "npm run build && ./publish.sh --version=0.0.1" }, "dependencies": { ... } "devDependencies": { ... } } |
Calling
1 |
npm run deploy |
the contents inside folder dist/js and dist/css will be deleted, then webpack is called to bundlerize the project and the ‘publish.sh’ shell script is invoked to publish to some server the 0.0.1 version of the software.
This is a simple tips to modify and adapt to your development environment.
Types
There are some ‘special‘ types of scripts that NPM automatically recognizes before/in/after the specific phase on installing and downloading a package from the NPM repository: this is an overview of it
On the other hand it is possible to write ‘custom‘ scripts to perform some specific tasks as we have seen in the previous paragraph.
The potential of NPM Scripts is enormous: we will return to this topic with other tips in the next articles.
We’re always looking for talented developers… find out all open job positions!