gulpgulp-inject

How to inject files in special place of file using gulp


I am going to inject some js and css files into index.html, I create the array of paths to files :

var paths = {
   js: [
      'a.js',
      '/b/b.js',
      '/c/d/d.js
   ],
   css: [
      'a/a.css',
      'b/b/b.css'
   ]
}

in my index.html file :

 <!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <title>INDEX</title>
     <!-- inject:css -->
     <!-- endinject -->
 </head>
 <body>

 <!-- inject:js -->
 <!-- endinject -->

 <h1>Hello Index</h1>

 </body>
 </html>

and my gulp task is :

 gulp.task('index', function () {
   var target = gulp.src('./index.html');

   var sources = gulp.src([paths.js, paths.css], {read: false});

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

How can I place these files in index.html?


Solution

  • Using gulp-inject package

    inject = require('gulp-inject')
    

    Gulp task will be like this

    gulp.task('TASK_NAME', function() {
      var target = gulp.src('./RAW.html');
      return target
        .pipe(inject(gulp.src([...]), {
          read: false
        }), {
          name: 'NAME_IN_HTML'
        }));
    });
    

    And in RAW.html insert this in place:

    <!-- inject:NAME_IN_HTML -->
    <!-- endinject -->