Speed up your entire Grunt build process with a single plugin: jit-grunt

Datetime:2016-08-23 02:44:41          Topic: Grunt           Share

Every Grunt project averages 20 plugins per build. And – if you ever used Grunt , and chances are you have – you know it can ramp up to 30 plugins very quickly.

Problem

The standard Grunt way of loading plugins is adding a grunt.loadNpmTasks for each plugin you use. They look like this:

grunt.loadNpmTasks('grunt-contrib-htmlmin');
grunt.loadNpmTasks('grunt-contrib-imagemin');
grunt.loadNpmTasks('grunt-contrib-browser-sync');
grunt.loadNpmTasks('grunt-contrib-cssnano');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-newer');
grunt.loadNpmTasks('grunt-mocha');

That’s a lot of lines of code we’d all rather not have to write and skim through in our Gruntfile.js . It’s repetitive. Those plugins are already in our package.json file and all we’re doing here is iterating through a list and calling the loadNpmTasks method.

And every time we install a plugin we have to remember add it to the list. Every time we uninstall a plugin, we have to also remove it from the list.

Another downside is that method of loading plugins can take about 6 to 8 seconds! Or more. That’s per build. A slowdown to our build process is not what we need.

Solution

There’s a Grunt plugin that does all that for you, in the background, and does it fast. It’s called jit-grunt and you can install it via npm :

npm i jit-grunt--save-dev

After that, all you have to do is add one line to your Gruntfile.js :   require('jit-grunt')(grunt).

The top part of your Gruntfile.js will look a lot like this:

module.exports = function (grunt) {
  require('jit-grunt')(grunt);

  grunt.initConfig({
    ...
  });

  ...
}

That’s it! jit-grunt will scout through your node_modules folder for all the plugins your Grunt tasks require, and will load them only as they are needed. For every packagename jit-grunt will look for three variants: grunt-contrib-packagename , grunt-packagename and just packagename , in order, until it finds the right plugin. And it will load the plugin for you.

You can now do without all those redundant loadNpmTasks lines and not just that:  you magically end up saving precious seconds for every build. That 6 to 8 seconds slowdown we referred to before? Gone.

And what did we learn?

Gruntis a terrific build tool we all love and use, but the standard way of loading plugins takes a lot of real estate in our Gruntfile.js and slows down the build process. There’s a way to fix that: all we have to do is get jit-grunt and let it do all the work for us.

Learn more on installation and usage on the jit-grunt GitHub page . jit-grunt was created by  Shotaro Tsubouchi .





About List