Created
November 7, 2019 14:16
-
-
Save TerribleDev/8677821c3e174659250df1f6bba9d7c3 to your computer and use it in GitHub Desktop.
Webpack 4 plugin to measure how long an entry takes to build
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { performance, PerformanceObserver } = require('perf_hooks'); | |
const PluginName = "TimeReporterPlugin"; | |
class TimeReporterPlugin { | |
constructor(filterPattern = /HtmlWebpackPlugin|mini-css-extract-plugin/i) { | |
this.FilterPattern = filterPattern; | |
} | |
apply(compiler) { | |
let _timeEvents = []; | |
const createEventFromEntry = entry => ({ | |
name: entry.name, | |
package: process.env.npm_package_name, | |
duration: Math.round(entry.duration), | |
}); | |
const obs = new PerformanceObserver((items) => { | |
_timeEvents = _timeEvents.concat(items.getEntries().map(entry => (createEventFromEntry(entry)))); | |
}); | |
obs.observe({ entryTypes: ['measure'] }); | |
const start = name => (`${name} - start`); | |
const end = name => (`${name} - end`); | |
const entryAdd = newEntry => { | |
try { | |
const { loc: { name = "" } = {} } = newEntry || {}; | |
if (!name.match(this.FilterPattern)) { | |
performance.mark(start(name)); | |
} | |
} catch (e) { | |
console.warn(`${PluginName}: ${e}`); | |
} | |
}; | |
const entryDone = (_ent, name) => { | |
try { | |
if (!name.match(this.FilterPattern)) { | |
performance.mark(end(name)); | |
performance.measure(name, start(name), end(name)); | |
} | |
} catch (e) { | |
console.warn(`${PluginName}: ${e}`); | |
} | |
}; | |
compiler.hooks.compilation.tap(PluginName, compilation => { | |
compilation.hooks.addEntry.tap(PluginName, entryAdd); | |
compilation.hooks.failedEntry.tap(PluginName, entryDone); | |
compilation.hooks.succeedEntry.tap(PluginName, entryDone); | |
}); | |
const onDone = async (stats, done) => { | |
try { | |
//TODO: Log these events somewhere ;) | |
console.log(_timeEvents); | |
performance.clearMarks(); | |
} catch { | |
stats.compilation.warnings.push(`${PluginName}: Error reporting timing statistics`); | |
} finally { | |
done(); | |
} | |
}; | |
compiler.hooks.done.tapAsync(PluginName, onDone); | |
} | |
} | |
module.exports = TimeReporterPlugin; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a sample of how to make a webpack plugin to time how long entries take to build. You should edit the comment on line 57 and actually send your data somwhere