Via G. Falcone 5, Pollenza (MC), Italy
+39 0733 203595

NPM Scripts: a valid support for the developer

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:

  1. their ease of use
  2. the wide adoption of the Node / NPM ecosystem
  3. 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)

Calling

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

Calling

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!

 

Related Posts

Leave a reply