Catfish
Catfish

Reputation: 19294

Gulp inject not working one way but works the other - no difference is there?

I have a gulp task to inject bower components into my index.html file. I have 2 different versions of it and one works and one does not and I can't tell why the one does not work b/c it looks exactly the same to me.

Does NOT work

var gulp = require('gulp');
var inject = require('gulp-inject');
var mainBowerFiles = require('main-bower-files');

/**
 * Injects all the bower dependencies into index.html
 */
gulp.task('inject-bower-files', function() {
  return 
    gulp.src('./index.html')
      .pipe(inject(gulp.src(mainBowerFiles(), {read: false})))
      .pipe(gulp.dest('./'));
});

Works

var gulp = require('gulp');
var inject = require('gulp-inject');
var mainBowerFiles = require('main-bower-files');

/**
 * Injects all the bower dependencies into index.html
 */
gulp.task('inject-bower-files', function() {

  var target = gulp.src('./index.html');
  var sources = gulp.src(mainBowerFiles(), {read: false});

  return target.pipe(inject(sources))
    .pipe(gulp.dest('./'));
});

What is the difference between these two?

Upvotes: 0

Views: 170

Answers (1)

psalaets
psalaets

Reputation: 717

Your first example is failing due to JavaScript's automatic semicolon insertion.

It is equivalent to

var gulp = require('gulp');
var inject = require('gulp-inject');
var mainBowerFiles = require('main-bower-files');

/**
 * Injects all the bower dependencies into index.html
 */
gulp.task('inject-bower-files', function() {
  return; // <-- semicolon inserted here, nothing below this runs
    gulp.src('./index.html')
      .pipe(inject(gulp.src(mainBowerFiles(), {read: false})))
      .pipe(gulp.dest('./'));
});

To make it work, change it to

var gulp = require('gulp');
var inject = require('gulp-inject');
var mainBowerFiles = require('main-bower-files');

/**
 * Injects all the bower dependencies into index.html
 */
gulp.task('inject-bower-files', function() {
  // return is no longer on a line by itself
  return gulp.src('./index.html')
      .pipe(inject(gulp.src(mainBowerFiles(), {read: false})))
      .pipe(gulp.dest('./'));
});

Upvotes: 2

Related Questions