Search code examples
browserify

How can I make browserify onComplete handlers wait for my plugin to finish?


I'm writing a browserify plugin which adds a transform but also needs to do things at the very end, once browserify has finished going through the require tree. Achieving this is simple since my plugin receives a browserify instance (which I call brow), so I can just brow.transform(...) to add my transform and use the following to do more at the end:

brow.on('bundle', function (bundler) {
  bundler.on('end', doMoreAtTheEnd)
})

This works fine except for one pretty important detail. Any other handlers expected to run when browserify is done (via the onComplete handler brow.bundle(onComplete)) execute too soon (before my plugin is done doing it's work). This makes testing my plugin rather difficult, for example, since the assertions I wrote in the onComplete handler execute before my plugin is done doing its work.

I understand why this happens: my plugin and my assertions are both using the same onComplete event, so they will run one immediately before the other, and since my plugin is doing async work, the assertions run too soon). but I'm not sure how to achieve what I want without extreme hackery... I could use setTimeout, of course, but I'm trying to avoid that, for reasons that should be obvious...

Any ideas?

update I've reduced my problem to a short gist, if that helps


Solution

  • I found a solution using the browserify pipeline. The trick is to use the flush callback of the last phase in the pipeline (wrap).

    var through = require('through2')
    var wrap = brow.pipeline.get('wrap')
    wrap.push(through(function (buf, enc, next) {
      // This leaves the chunks unchanged
      this.push(buf)
      next()
    }, function (next) {
      // Here I can do some async work
      setTimeout(function () {
        // and call `next` when I'm done
        next()
      }, 1000)
    })
    

    I made a new gist which applies this fix to the original gist illustrating the problem in the question.