Using Npm Scripts With Grunt

Paul Bill


Paul Bill
I have seen a few arguments recently for ditching grunt (or gulp for that matter) in favour of using Npm’s scripts as a build tool. I depend on grunt too much to be in that boat, however if you use Grunt you can make use of Npm’s scripts to make your life a little easier and save keyboard wear!
You can use grunt for many build tasks, and i usually end up creating an install task. This install task could compile your SASS, and if your working with Magento, perhaps install your modman extensions:
grunt.loadNpmTasks( 'grunt-sass' );
grunt.loadNpmTasks( 'grunt-modman' );
grunt.loadNpmTasks( 'grunt-modernizr' );
grunt.loadNpmTasks( 'grunt-scss-lint' );
grunt.registerTask( 'install', ['modman', 'sass', 'modernizr'] );
Then you or someone else comes to install the project they would have to type:
npm install
grunt install
Npm’s scripts are defined in your package.json
file, and these scripts can be executed as pre or post hooks.
One of the most handy hooks in my opinion is the postinstall hook.
Using the postinstall hook we can tell npm to automatically run grunt install, as soon as our npm dependencies are downloaded.
To do this add the following to your package.json
file:
"scripts": {
"postinstall": "grunt install"
}
Now we only need to type npm install
and our grunt install build task will also be run automatically.
Pretty cool.
But what if we have different build tasks for installation depending on the installation environment?
Well we can access those in our Gruntfile.js
:
var installTasks = process.env.NODE_ENV === 'production' ?
['modman', 'sass', 'modernizr'] :
['modman', 'sass', 'scsslint', 'modernizr'];
grunt.registerTask( 'install', installTasks );
Running our install command with an environment variable set will now trigger a different set of build tasks.
npm install --production