diff --git a/index.js b/index.js index 5f35e94..5ce457e 100644 --- a/index.js +++ b/index.js @@ -1,7 +1,14 @@ -require("./lib/profiler")(); +const profile = require("./lib/profiler"); let isListeningOnStdin = false; +const defaultOpts = { + profilePath: void 0, + open: true // auto open the generated html +}; module.exports = class CpuProfileWebpackPlugin { + constructor(opts) { + profile(Object.assign({}, defaultOpts, opts)); + } apply(compiler) { compiler.hooks.watchRun.tapAsync( "CpuProfileWebpackPlugin", diff --git a/lib/profiler.js b/lib/profiler.js index fbb9422..550bd2d 100644 --- a/lib/profiler.js +++ b/lib/profiler.js @@ -1,6 +1,7 @@ const { readFileSync, writeFileSync } = require("fs"); const path = require("path"); const cpuProfiler = require("sync-cpuprofiler"); +const opn = require("open"); /** * Extract the package versions from the node require cache @@ -82,7 +83,8 @@ function getUsedNodeModules() { ); } -function writeProfileFiles(profilePath, options) { +function writeProfileFiles(options) { + const { profilePath, open, ...opts } = options; function onProfileDone(profilePath) { const profile = readFileSync(profilePath, "utf-8"); const html = readFileSync( @@ -97,7 +99,9 @@ function writeProfileFiles(profilePath, options) { /* after %~~%profile%~~% before %~~%versions%~~% */ htmlParts[2] + versions + /* after %~~%versions%~~% */ htmlParts[4]; - writeFileSync(profilePath + ".html", htmlResult); + const htmlPath = profilePath + ".html"; + writeFileSync(htmlPath, htmlResult); + open && opn(htmlPath); console.log( "⏱️ Profile written to ", path.relative(process.cwd(), profilePath + ".html") @@ -107,9 +111,9 @@ function writeProfileFiles(profilePath, options) { cpuProfiler(profilePath, Object.assign({}, options, { onProfileDone })); } -module.exports = (profilePath, options) => { +module.exports = options => { try { - return writeProfileFiles(profilePath, options); + return writeProfileFiles(options); } catch (e) { console.log("Writting profile failed", e); } diff --git a/package.json b/package.json index 844a5e7..8bf7edc 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "prepublishOnly": "npm run build" }, "dependencies": { + "open": "^7.0.3", "sync-cpuprofiler": "1.1.3" }, "peerDependencies": {