Automatically require plugins in Gulp

Many of my posts are related to my development workflow using Gulp (eg. 1234, etc.), and the code in these posts tends to follow a familiar pattern:

  1. Install a plugin with NPM
  2. Require the plugin at the top of the Gulpfile
  3. Add a new task or update an existing one that uses the new plugin

So it would be good if we could skip out one of those steps and everything still work, right?

Right! Introducing another plugin; gulp-load-plugins.

We’re going to follow the steps with this one, so here goes, step one…

npm install --save-dev gulp-load-plugins

And then step two…

var plugins = require("gulp-load-plugins")();

But in this case, there’s no step three.  Please note the extra brackets on the end of the require.  This is very important because it actually runs the plugin, not just loads it in.

Let’s take a simple example from a previous post about using PostCSS partials using Gulp

var gulp = require("gulp");
var postcss = require("gulp-postcss");
var cssnext = require("postcss-cssnext");
var partials = require("postcss-partial-import");

var css = function() {
  return gulp.src(cssFiles)
    .pipe(postcss([
      partials({prefix:"_",extension:".css"}),
      cssnext()
    ]))
    .pipe(gulp.dest("build/css"));
};

You can see that we need to require Gulp itself and then the 3 plugins that this task is using.  With a more complete Gulp file, the number of require‘s can grow really quite big.

However, now that we’ve installed gulp-load-plugins, we can simply this as follows…

var gulp = require("gulp");
var plugins = require("gulp-load-plugins")();

var css = function() {
  return gulp.src(cssFiles)
    .pipe(plugins.postcss([
      plugins.partials({prefix:"_",extension:".css"}),
      plugins.cssnext()
    ]))
    .pipe(gulp.dest("build/css"));
};

As you can see, the only require that we need after Gulp is our new plugin.  This plugin reads the “package.json” file and automatically require‘s all of the dependencies, making them available as methods of the created variable (“plugins” in this example) with the same name.  This means that each time we want to call a plugin, we simply add “plugins.” in front of it, and the rest of our code remains the same.

Moving forwards, this means that there is no need to add any more require statements, as the act of installing them (which adds them to the “package.json file”) will mean that they will be loaded in a made available.  And that’s precious seconds saved, am I right?

I don’t plan to use this in my future examples, as it might take confusing when taken out of context by landing on a particular post, but it’s something that I introduced and used in my Optimising your website: A development workflow continued with Gulp 4 course.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.