How to add src files in the middle of a pipe

2019-01-22 06:31发布

问题:

I want to process some files with 'coffee', add some js files, concat and minify.

This does not work, coffee fails on the regular js files:

gulp.task 'build-js', ->
  gulp.src([
      "bower_components/mbdev-core/dist/js/db.js"
      "bower_components/mbdev-core/dist/js/utils.js"
      "src/js/config/app.coffee"
      "src/js/config/app-db.coffee"              
      "src/js/accounts/accounts.coffee"
      "src/js/budget_items/budget_items.coffee"
      "src/js/line_items/line_items.coffee"
      "src/js/misc/misc.coffee"
      "src/js/reports/report_generators.coffee"
      "src/js/reports/reports.coffee"
   ])
  .pipe(coffee()).on('error', gutil.log)
  .pipe(concat('app.js'))
  .pipe(gulp.dest('public/js'))

Is there a way to add files after the coffee part?

回答1:

You don't need to add files to the original src, but rather to use coffee only "if"...

So, use gulp-if

gulp.task('task', function() {
  gulp.src('./stuff/*')
    .pipe(gulpif(/[.]coffee$/, coffee()))
    .pipe(gulp.dest('./dist/'));
});

See here more about gulp-if.



回答2:

@Contra 's answer doesn't work for me. New stream replaced the old one, not joined them.

You should combine streams in this way:

es = require("event-stream")

es.concat(
  gulp.src('*.coffee')
  .pipe(coffee()),
  gulp.src('*.js')
).pipe(concat('all.js'))
.pipe(gulp.dest('.'))

And you can see official guide about this here Using multiple sources in one task

If you care about the order inside the stream, you should use streamqueue instead of event-stream



回答3:

You can use the gulp-add-src plugin:

addsrc = require 'gulp-add-src'

gulp.task 'build-js', ->
  gulp.src(['src/coffee/*.coffee'])
    .pipe(coffee()).on('error', gutil.log)
    .pipe(addsrc(['src/js/somefile.js', 'src/js/otherfile.js']))
    .pipe(concat('app.js'))
    .pipe(gulp.dest('public/js'))


回答4:

gulp.src streams are passthroughs so you can add them at any point in the pipeline

gulp.task 'build-js', ->
  gulp.src([
      "src/js/config/app.coffee"
      "src/js/config/app-db.coffee"              
      "src/js/accounts/accounts.coffee"
      "src/js/budget_items/budget_items.coffee"
      "src/js/line_items/line_items.coffee"
      "src/js/misc/misc.coffee"
      "src/js/reports/report_generators.coffee"
      "src/js/reports/reports.coffee"
  ])
  .pipe(coffee()).on('error', gutil.log)
  .pipe(gulp.src([
      "bower_components/mbdev-core/dist/js/db.js"
      "bower_components/mbdev-core/dist/js/utils.js"
  ]))
  .pipe(concat('app.js'))
  .pipe(gulp.dest('public/js'))