Search code examples
gulpgulp-inject

Gulp cannot inject css and js at the same time


I am trying to run the following code

var $ = require('gulp-load-plugins')({ lazy: true }); // fetches gulp plugins

gulp.task('wiredep', function () {
     var wiredep = require('wiredep').stream;

    return gulp
    .src(config.index)
    .pipe(wiredep(config.wiredepDefaultOptions))      //wiredep injection configuration
    .pipe($.inject(gulp.src(config.js)))              //custom js files configuation
    .pipe(gulp.dest(config.client))
});



/* inject bower and other injections */
   gulp.task('inject', ['styles-compile', 'wiredep'], function () {
     return gulp
       .src(config.index)
       .pipe($.inject(gulp.src(config.css)))
       .pipe(gulp.dest(config.client))
});

// if I comment the following line .pipe($.inject(gulp.src(config.css)))

Then my .js files get inject otherwise they do not, from what I understand this injection happens in parallel.

What am I doing wrong?


Solution

  • gulp-inject will only inject one set of files, replacing the old set with the new set each time you call it. There are two ways to solve the problem.

    1) From the gulp-inject github page: use the event-stream plugin to combine the two streams of filenames (.css and .js) into a single stream which you pass to inject.

    var es = require('event-stream'),
        inject = require('gulp-inject');
    
    // Concatenate vendor scripts
    var vendorStream = gulp.src(['./src/vendors/*.js'])
      .pipe(concat('vendors.js'))
      .pipe(gulp.dest('./dist'));
    
    // Concatenate AND minify app sources
    var appStream = gulp.src(['./src/app/*.js'])
      .pipe(concat('app.js'))
      .pipe(uglify())
      .pipe(gulp.dest('./dist'));
    
    gulp.src('./src/index.html')
      .pipe(inject(es.merge(vendorStream, appStream)))
      .pipe(gulp.dest('./dist'));
    

    2) An alternative solution which may suit your current code organisation better is to use the gulp-inject name parameter to define two different places to inject. Thus you have a header file like this:

    <!DOCTYPE html>
    <html>
      <head>
        <title>My index</title>
      <!-- styles:css -->
      <!-- the styles files will be injected here -->
      <!-- endinject -->
    </head>
    <body>
    
      <!-- scripts:js -->
      <!-- the scripts files will be injected here -->
      <!-- endinject -->
    </body>
    </html>
    

    and then your gulpfile.js contains something like:

    var inject = require('gulp-inject');
    
    gulp.src('./src/index.html')
      .pipe(inject(gulp.src('./config.css'), {name: 'styles'}))
      .pipe(inject(gulp.src('./config.js'), {name: 'scripts'}))
      .pipe(gulp.dest('./dist'));