Skip to content

Commit

Permalink
Merge pull request #102 from th0r/new-options
Browse files Browse the repository at this point in the history
Add custom reporter configuration
  • Loading branch information
valscion authored Jul 17, 2017
2 parents f6d99c0 + e73619d commit fec9b6d
Show file tree
Hide file tree
Showing 10 changed files with 111 additions and 97 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"dev": "lerna run start --parallel",
"npm-publish": "npm run lint && npm run build && npm test && lerna publish",
"test": "lerna run test --stream",
"test-dev": "lerna run test-dev --parallel",
"lint": "eslint --ext js,jsx ."
},
"devDependencies": {
Expand Down
56 changes: 29 additions & 27 deletions packages/plugin/src/BundleAnalyzerPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,39 @@ const { bold } = require('chalk');

const Logger = require('./Logger');
const analyzer = require('./analyzer');
const reporter = require('@webpack-bundle-analyzer/reporter-treemap');

class BundleAnalyzerPlugin {

constructor(opts) {
const {
reporter,
reporterOptions,
...pluginOptions
} = opts;

this.opts = {
analyzerMode: 'server',
analyzerHost: '127.0.0.1',
analyzerPort: 8888,
reportFilename: 'report.html',
defaultSizes: 'parsed',
openAnalyzer: true,
generateStatsFile: false,
statsFilename: 'stats.json',
statsOptions: null,
logLevel: 'info',
// deprecated
startAnalyzer: true,
...opts
...pluginOptions
};

if (!reporter) {
// TODO: Improve this error message a lot, as this will be the first
// error of backwards-incompatibility compared to v2
throw new Error('options.reporter is not set!');
}
if (typeof reporter !== 'string') {
// We can't support passing `reporter: require('my-reporter')` syntax as
// if we did, we'd have no way of ensuring CLI works, too.
// TODO: Improve this error message, explain about options.reporterOptions
throw new Error('options.reporter is not a string!');
}
this.reporter = require(reporter);
this.reporterOptions = reporterOptions || {};

this.server = null;
this.logger = new Logger(this.opts.logLevel);
}
Expand All @@ -42,11 +54,6 @@ class BundleAnalyzerPlugin {
actions.push(() => this.generateStatsFile(stats));
}

// Handling deprecated `startAnalyzer` flag
if (this.opts.analyzerMode === 'server' && !this.opts.startAnalyzer) {
this.opts.analyzerMode = 'disabled';
}

if (this.opts.analyzerMode === 'server') {
actions.push(() => this.startAnalyzerServer(stats));
} else if (this.opts.analyzerMode === 'static') {
Expand Down Expand Up @@ -82,25 +89,20 @@ class BundleAnalyzerPlugin {
if (this.server) {
(await this.server).updateData(chartData);
} else {
this.server = reporter.createReporter(chartData, {
openBrowser: this.opts.openAnalyzer,
host: this.opts.analyzerHost,
port: this.opts.analyzerPort,
bundleDir: this.getBundleDirFromCompiler(),
logger: this.logger,
defaultSizes: this.opts.defaultSizes
this.server = this.reporter.createReporter(chartData, {
...this.reporterOptions,
outputPath: this.compiler.outputPath,
logger: this.logger
});
}
}

generateStaticReport(stats) {
const chartData = analyzer.getChartData(this.logger, stats, this.getBundleDirFromCompiler());
reporter.generateReport(chartData, {
openBrowser: this.opts.openAnalyzer,
reportFilename: path.resolve(this.compiler.outputPath, this.opts.reportFilename),
bundleDir: this.getBundleDirFromCompiler(),
logger: this.logger,
defaultSizes: this.opts.defaultSizes
this.reporter.generateReport(chartData, {
...this.reporterOptions,
outputPath: this.compiler.outputPath,
logger: this.logger
});
}

Expand Down
75 changes: 29 additions & 46 deletions packages/plugin/src/bin/analyzer.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,6 @@ const { magenta } = require('chalk');

const Logger = require('../Logger');
const analyzer = require('../analyzer');
const reporter = require('@webpack-bundle-analyzer/reporter-treemap');

const SIZES = new Set(['stat', 'parsed', 'gzip']);

const program = commander
.version(require('../../package.json').version)
Expand All @@ -33,52 +30,43 @@ const program = commander
'server'
)
.option(
'-h, --host <host>',
'Host that will be used in `server` mode to start HTTP server.' +
br('Default is `127.0.0.1`.'),
'127.0.0.1'
)
.option(
'-p, --port <n>',
'Port that will be used in `server` mode to start HTTP server.' +
br('Default is 8888.'),
Number,
8888
'-r, --reporter <reporter>',
'The reporter package to use, e.g. @webpack-bundle-analyzer/reporter-treemap'
)
.option(
'-r, --report <file>',
'Path to bundle report file that will be generated in `static` mode.' +
br('Default is `report.html`.'),
'report.html'
)
.option(
'-s, --default-sizes <type>',
'Module sizes to show in treemap by default.' +
br(`Possible values: ${[...SIZES].join(', ')}`) +
br('Default is `parsed`.'),
'parsed'
)
.option(
'-O, --no-open',
"Don't open report in default browser automatically."
'-R, --reporter-options <options>',
'The options to pass to the reporter you use as a valid JSON object.' +
br('Consult the reporter documentation for available options.'),
'{}'
)
.parse(process.argv);

let {
mode,
host,
port,
report: reportFilename,
defaultSizes,
open: openBrowser,
reporter,
reporterOptions,
args: [bundleStatsFile, bundleDir]
} = program;

if (!bundleStatsFile) showHelp('Provide path to Webpack Stats file as first argument');
if (mode !== 'server' && mode !== 'static') showHelp('Invalid mode. Should be either `server` or `static`.');
if (mode === 'server' && !host) showHelp('Invalid host name');
if (mode === 'server' && isNaN(port)) showHelp('Invalid port number');
if (!SIZES.has(defaultSizes)) showHelp(`Invalid default sizes option. Possible values are: ${[...SIZES].join(', ')}`);
if (!reporter) {
// TODO: Improve this error message a lot, as this will be the first
// error of backwards-incompatibility compared to v2
throw new Error('reporter is not set!');
}
if (typeof reporter !== 'string') {
// TODO: Improve this error message
throw new Error('reporter is not a string!');
}
reporter = require(reporter);
// TODO: Allow same format as webpack --env flag, i.e.
// `--reporter-options.host=1234` to set `reporterOptions = { host: 1234 }`
reporterOptions = JSON.parse(reporterOptions);

if (typeof reporterOptions !== 'object') {
throw new Error('reporterOptions must be an object!');
}

bundleStatsFile = resolve(bundleStatsFile);

Expand All @@ -97,19 +85,14 @@ const chartData = analyzer.getChartData(logger, bundleStats, bundleDir);

if (mode === 'server') {
reporter.createReporter(chartData, {
openBrowser,
port,
host,
defaultSizes,
bundleDir,
...reporterOptions,
outputPath: process.cwd(),
logger
});
} else {
reporter.generateReport(chartData, {
openBrowser,
reportFilename: resolve(reportFilename),
defaultSizes,
bundleDir,
...reporterOptions,
outputPath: process.cwd(),
logger
});
}
Expand Down
13 changes: 12 additions & 1 deletion packages/plugin/test/analyzer.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,18 @@ describe('Analyzer', function () {
});

function generateReportFrom(statsFilename) {
childProcess.execSync(`../lib/bin/analyzer.js -m static -r output/report.html -O stats/${statsFilename}`, {
const rOpts = JSON.stringify({
reportFilename: 'output/report.html',
openBrowser: false
});
const execArgs = [
'../lib/bin/analyzer.js',
'-m static',
'--reporter=@webpack-bundle-analyzer/reporter-treemap',
`--reporter-options='${rOpts}'`,
`stats/${statsFilename}`
].join(' ');
childProcess.execSync(execArgs, {
cwd: __dirname
});
}
Expand Down
4 changes: 1 addition & 3 deletions packages/plugin/test/dev-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ describe('Webpack Dev Server', function () {

this.timeout(timeout);

const devServer = exec(`${__dirname}/../node_modules/.bin/webpack-dev-server --config ${WEBPACK_CONFIG_PATH}`, {
cwd: `${ROOT}/tmp`
});
const devServer = exec(`${__dirname}/../node_modules/.bin/webpack-dev-server --config ${WEBPACK_CONFIG_PATH}`);

const reportCheckIntervalId = setInterval(() => {
if (fs.existsSync(`${webpackConfig.output.path}/report.html`)) {
Expand Down
2 changes: 0 additions & 2 deletions packages/plugin/test/dev-server/tmp/.gitignore

This file was deleted.

7 changes: 5 additions & 2 deletions packages/plugin/test/dev-server/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@ module.exports = {
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: 'static',
reportFilename: 'report.html',
openAnalyzer: false
reporter: '@webpack-bundle-analyzer/reporter-treemap',
reporterOptions: {
reportFilename: 'report.html',
openBrowser: false
}
})
]
};
7 changes: 5 additions & 2 deletions packages/plugin/test/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,11 @@ function makeWebpackConfig(opts) {
opts = {
analyzerOpts: {
analyzerMode: 'static',
openAnalyzer: false,
logLevel: 'error'
logLevel: 'error',
reporter: '@webpack-bundle-analyzer/reporter-treemap',
reporterOptions: {
openBrowser: false
}
},
minify: false,
multipleChunks: false,
Expand Down
20 changes: 18 additions & 2 deletions packages/reporter-treemap/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,27 @@ module.exports = {
};

function generateReport(stats, opts) {
return viewer.generateReport(stats, opts);
const parsedOpts = {
host: '127.0.0.1',
port: 8888,
defaultSizes: 'parsed',
openBrowser: true,
outputPath: opts.outputPath,
reportFilename: opts.reportFilename || 'report.html',
...opts
};
return viewer.generateReport(stats, parsedOpts);
}

function createReporter(initialChartData, opts) {
const server = viewer.startServer(initialChartData, opts);
const parsedOpts = {
host: '127.0.0.1',
port: 8888,
defaultSizes: 'parsed',
openBrowser: true,
...opts
};
const server = viewer.startServer(initialChartData, parsedOpts);
return server.then(({ updateChartData }) => ({
updateData: newData => {
updateChartData(newData);
Expand Down
23 changes: 11 additions & 12 deletions packages/reporter-treemap/src/viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,12 @@ module.exports = {

async function startServer(chartData, opts) {
const {
port = 8888,
host = '127.0.0.1',
openBrowser = true,
// bundleDir = null,
port,
host,
openBrowser,
logger,
defaultSizes = 'parsed'
} = opts || {};
defaultSizes
} = opts;

if (!logger) {
throw new Error('opts.logger is missing');
Expand Down Expand Up @@ -93,12 +92,12 @@ async function startServer(chartData, opts) {

function generateReport(chartData, opts) {
const {
openBrowser = true,
reportFilename = 'report.html',
bundleDir = null,
openBrowser,
reportFilename,
outputPath,
logger,
defaultSizes = 'parsed'
} = opts || {};
defaultSizes
} = opts;

if (!logger) {
throw new Error('opts.logger is missing');
Expand All @@ -117,7 +116,7 @@ function generateReport(chartData, opts) {
(err, reportHtml) => {
if (err) return logger.error(err);

const reportFilepath = path.resolve(bundleDir || process.cwd(), reportFilename);
const reportFilepath = path.resolve(outputPath, reportFilename);

mkdir.sync(path.dirname(reportFilepath));
fs.writeFileSync(reportFilepath, reportHtml);
Expand Down

0 comments on commit fec9b6d

Please sign in to comment.