Simplifying Grunt Setup Using NPM Scripts

Before using Grunt we often need to run quite a few commands to install prerequisites and dependencies.

We would like to run grunt task:target, but before we can do that we may have to install Grunt, Bower or fetch dependencies. This may vary from project to project, so sometimes getting up and running can be quite a chore. Fortunately this problem can be easily solved by using NPM scripts.

When you run an NPM script it automatically runs pre and post hooks

{
  "name": "example", 
  "scripts": {
    "pregrunt": "npm i -g grunt-cli && npm i",
    "grunt": "grunt"
  }
}

With this setup we need to run npm run grunt task:target which will automatically run pregrunt and install everything we need.


We can take it a step further by having a release build which leverages pregrunt to install our dependencies and postrelease to remove files that we do not want released.

{
  "name": "example", 
  "scripts": {
    "pregrunt": "npm i -g grunt-cli && npm i",
    "grunt": "grunt",
    "release": "npm run grunt -- release",
    "postrelease": "npm i -g rimraf && rimraf node_modules && rimraf .sass-cache"
  }
}

For this, all we need to do is run npm run release.