Search code examples
javascriptwebpackwebpack-dev-middleware

How to do custom formatting of build stats with webpack-dev-middleware?


I am currently using the basic Webpack API with a custom printer for the build results, i.e.:

import webpack from 'webpack'

webpack({ /* webpack config */ }, printStats)

function printStats(err, stats) {
  // my custom printing of build results
}

Now I want to switch to using webpack-dev-middleware, but retain my stat printer. I would expect maybe this to work:

import webpackDev from 'webpack-dev-middleware'

app.use(webpackDev(webpack({ /* webpack config */ }, printStats), {
    quiet: true // disable default printing so I can use my own
    // ... more webpack-dev-middelware configuration
}))

but it only prints the first compilation and ignores subsequent ones even though they do take place. What is the right way to do this?


Solution

  • I solved this problem by listening directly to the Webpack compiler object via the plugin method:

    const compiler = webpack({ /* webpack config */ })
    
    compiler.plugin('done', stats => {
      // my custom printing of build results
    })
    
    app.use(webpackDev(compiler, {
      quiet: true // disable default printing so I can use my own
      // ... more webpack-dev-middelware configuration
    }))
    

    The done event occurs every time compilation finishes, successfully or otherwise. Other events you can listen to via the plugin method:

    • 'run': Indicates that a one-off compilation is taking place. Aynchronous; listener takes the compiler object and callback function which must be invoked to indicate the listener is done handling the event.
    • 'watch-run': Indicates that the source is being compiled or recompiled in watch mode. Aynchronous; listener takes the compiler object and callback function which must be invoked to indicate the listener is done handling the event.
    • 'invalid': Indicates that a change was detected to the source in the course of watching it (will be followed shortly by a watch-run event. Synchronous; listener takes no arguments.