Search code examples
javascriptnode.jswebpackbluebird

Webpack compiler instance promisification?


I'm using the Webpack 2 Node API and I would like to promisify the run() method using bluebird.

import Promise from 'bluebird'
import webpack from 'webpack'

const compiler = webpack(config)
const runAsync = Promise.promisify(compiler.run)

runAsync().then(stats => {
  console.log('stats:', stats)
}).catch(err => {
  console.log('err:', err)
})

The error I'm getting is:

[TypeError: self.applyPluginsAsync is not a function]

So I'm guessing that the webpack code isn't written in a way that's compatible with bluebird promisification.

If there any other way to promisify webpack's run() method..?

All these callbacks and if statements are bugging me.


Solution

  • You need to pass compiler as the context to the promisify method.

    const runAsync = Promise.promisify(compiler.run, { context: compiler });
    

    Or call it like so:

    runAsync.call(compiler).then(stats => {...
    

    From the Bluebird Docs:

    Note that if the node function is a method of some object, you can pass the object as the second argument like so:

    var redisGet = Promise.promisify(redisClient.get, {context: redisClient});
    redisGet('foo').then(function() {
        //...
    });