Last Updated: September 09, 2019
·
2.445K
· paulosborne

DRY up your Gruntfile

Until recently I had been loading Grunt tasks one per line - as suggested by the documentation. But pretty soon I ended up with an unsightly task list.

grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-less');

However, I recently stumbled upon a couple of alternative approaches to this. The first I found whilst browsing through Ghost on Github. They use an npm package called matchdep which allows you to filter dependencies in your package.json

npm install matchdep

Then in your Gruntfile, filter your devDependencies using..

require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

or your regular dependencies using

require('matchdep').filter('grunt-*').forEach(grunt.loadNpmTasks);

Alternatively, I came across another package called load-grunt-tasks while i was playing with Yeoman.

npm install load-grunt-tasks

and then in your Gruntfile

require('load-grunt-tasks')(grunt);

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside