Home  >  Q&A  >  body text

javascript - gulp-inject的使用方式

关于gulp-inject的使用方式,今天使用gulp构建项目,使用到了gulp-inject自动插入静态文件到html,但是纠结啦。

正常的使用方式

<!DOCTYPE html>
<html>
<head>
  <title>My index</title>
  <!-- inject:css -->
  <!-- endinject -->
</head>
<body>

  <!-- inject:js -->
  <!-- endinject -->
</body>
</html>
var gulp = require('gulp');
var inject = require('gulp-inject');

gulp.task('index', function () {
  var target = gulp.src('./src/index.html');
  // It's not necessary to read the files (will speed up things), we're only after their paths:
  var sources = gulp.src(['./src/**/*.js', './src/**/*.css'], {read: false});

  return target.pipe(inject(sources))
    .pipe(gulp.dest('./src'));
});
<!DOCTYPE html>
<html>
<head>
  <title>My index</title>
  <!-- inject:css -->
  <link rel="stylesheet" href="/src/style1.css">
  <link rel="stylesheet" href="/src/style2.css">
  <!-- endinject -->
</head>
<body>

  <!-- inject:js -->
  <script src="/src/lib1.js"></script>
  <script src="/src/lib2.js"></script>
  <!-- endinject -->
</body>
</html>

但是有个问题,这样的话,他会把全部的js跟css文件添加上去,我现在想要的是,比如index.html页面,只单独引入index.js和index.css,其他的就是公用的引入在一起比如,comm.js comm.css等,我希望是这样:

<!DOCTYPE html>
<html>
<head>
  <title>My index</title>
  <!-- inject:css -->
  <link rel="stylesheet" href="/src/comm.css">
  <link rel="stylesheet" href="/src/index.css">
  <!-- endinject -->
</head>
<body>

  <!-- inject:js -->
  <script src="/src/comm.js"></script>
  <script src="/src/index.js"></script>
  <!-- endinject -->
</body>
</html>

我该怎么配置,或者该怎么写注解??真心求教。

大家讲道理大家讲道理2654 days ago403

reply all(1)I'll reply

  • 大家讲道理

    大家讲道理2017-04-10 16:18:30

    gulp-inject 也可以自定义标签,
    你可以使用 starttag 配置

    var sourcesIndex = gulp.src(['./src/**/index.js', './src/**/index.css'], {read: false});
    var sourcesCommon = gulp.src(['./src/**/common.js', './src/**/common.css'], {read: false});
    
    gulp.src('./src/index.html')
        .pipe(inject(sourcesIndex, {starttag: '<!-- inject:index:{{ext}} -->'}))
        .pipe(inject(sourcesCommon, {starttag: '<!-- inject:common:{{ext}} -->'}))
        .pipe(gulp.dest('./dist'));
    <!DOCTYPE html>
    <html>
    <head>
      <title>My index</title>
      <!-- inject:common:css -->
      <!-- endinject -->
    
      <!-- inject:index:css -->
      <!-- endinject -->
    </head>
    <body>
      <!-- inject:common:js -->
      <!-- endinject -->
    
      <!-- inject:index:js -->
      <!-- endinject -->
    </body>
    </html>

    请参考这个 https://github.com/klei/gulp-inject#method-1-use-gulp-injects-starttag-option

    reply
    0
  • Cancelreply