如何使用gulp在文件的特殊位置注入文件

时间:2017-03-03 16:32:11

标签: gulp gulp-inject

我要将一些js和css文件注入index.html,我创建了文件路径数组:

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

在我的index.html文件中:

 <!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>

我的gulp任务是:

 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'));
 });

如何将这些文件放在index.html

1 个答案:

答案 0 :(得分:0)

使用gulp-inject

inject = require('gulp-inject')

Gulp任务将是这样的

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

RAW.html中插入此内容:

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