My Bower/Gulp settings

This is my Gulp.js workflow settings based on examples shown in this PluralSight course (I really recommend you to watch it).

I am using these gulp plugins:

When you install some library via bower you should do so with the –save option, so that it automatically updates the bower.json file. Like this

bower install angular --save

That will add following line to bower.json file:

 "dependencies": {
    "angular": "~1.4.8"
  }

Why do you need it?

Because the main-bower-files plugin will then read this “dependencies” section and inject listed scripts into the index.html file. Below is the responsible part of gulp configuration.

var mainBowerFiles = require('main-bower-files');
....
gulp.task('copyVendorScripts', function () {
 // call to mainBowerFiles() returns list of scripts
 // something like this: ['angular', 'satellizer', 'jquery'] etc...
 return gulp.src(mainBowerFiles())
 .pipe(gulp.dest('path/to/destination/folder'));
})

So, you do not really “need” to use the main-bower-files, but then you need to manually list the scripts in the section above. This way is just a bit more convenient and automatic. But I guess there are other ways how to achieve this goal.

How does inject work?

It basically filles placeholders in the index.html file. The sample index.html file may look like this:

<!DOCTYPE html>
<html>
<head>
  <title>Module</title>
  <!-- inject:css -->
  ALL CSS FILES WILL BE INJECTED HERE
  <!-- endinject -->
</head>
<body>
  <h1>Module</h1>
  <!-- inject:js -->
  ALL JS FILES WILL BE INJECTED HERE
  <!-- endinject --> 
</body> 
</html>

Most likely you will want to group your scripts into named sections. For example “vendor” scripts will contain all 3rd party libraries, such as AngularJs or jQuery etc. The “app” scripts will contain all your application logic. In order to achieve that you can use named sections, like this.

  <!-- vendorInject:js -->
  ALL VENDOR JS FILES WILL BE INJECTED HERE
  <!-- endinject --> 

  <!-- appInject:js -->
  ONLY APP SPECIFIC JS FILES WILL BE INJECTED HERE
  <!-- endinject -->

Your gulpfile will then look like this:

gulp.task('vendors', function () {

 var tempVendors = gulp.src('path/to/vendor/scripts', {
 read: false
 });

 return gulp.src('path/to/index.html/file')
  .pipe(inject(tempVendors, {
     relative: true,
     // the name must correspond to that in index.html
     name: 'vendorInject'
   }))
   .pipe(gulp.dest('path/to/destination/folder'));
});

 

PS: The described workflow is not from my head, but based on Alexander Zanfir’s. I am quite new to Gulp/Grunt/Bower etc tools, so comments and suggestions for improvements are welcomed and appreciated.

If anyone is interested, I’ve also created Github repository based on the Pluralsight course.