Skip to content

Commit

Permalink
feat: auto open generated html (fixes jantimon#10)
Browse files Browse the repository at this point in the history
it also fixes jantimon#7, by moving the function call to its constructor. :)
  • Loading branch information
aladdin-add committed Apr 10, 2020
1 parent fd8e71d commit 0917220
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
9 changes: 8 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
14 changes: 9 additions & 5 deletions lib/profiler.js
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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(
Expand All @@ -97,19 +99,21 @@ 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")
);
}

cpuProfiler(profilePath, Object.assign({}, options, { onProfileDone }));
cpuProfiler(profilePath, Object.assign({}, opts, { onProfileDone }));
}

module.exports = (profilePath, options) => {
module.exports = options => {
try {
return writeProfileFiles(profilePath, options);
return writeProfileFiles(options);
} catch (e) {
console.log("Writting profile failed", e);
}
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"prepublishOnly": "npm run build"
},
"dependencies": {
"open": "^7.0.3",
"sync-cpuprofiler": "1.1.3"
},
"peerDependencies": {
Expand Down

0 comments on commit 0917220

Please sign in to comment.