Skip to content

Commit

Permalink
refactor: use webpack logger
Browse files Browse the repository at this point in the history
  • Loading branch information
piecyk committed Nov 4, 2020
1 parent c261e65 commit 6c02ec7
Show file tree
Hide file tree
Showing 3 changed files with 128 additions and 69 deletions.
118 changes: 85 additions & 33 deletions packages/webpack-cli/lib/plugins/WebpackCLIPlugin.js
@@ -1,62 +1,114 @@
const { packageExists } = require('../utils/package-exists');
const webpack = packageExists('webpack') ? require('webpack') : undefined;
const logger = require('../utils/logger');
const { getStatsOptions } = require('../utils/stats-options');

const PluginName = 'webpack-cli';

const appendProgressPlugin = (compiler, progress) => {
const { ProgressPlugin } = compiler.webpack || webpack;

const logger = compiler.getInfrastructureLogger(PluginName);

const compilers = compiler.compilers || [compiler];

for (const compiler of compilers) {
let progressPluginExists;

if (compiler.options.plugins) {
progressPluginExists = Boolean(compiler.options.plugins.find((plugin) => plugin instanceof ProgressPlugin));
}

if (!progressPluginExists) {
if (typeof progress === 'string' && progress !== 'profile') {
logger.error(`'${progress}' is an invalid value for the --progress option. Only 'profile' is allowed.`);

process.exit(2);
}

const isProfile = progress === 'profile';

new ProgressPlugin({ profile: isProfile }).apply(compiler);
}
}
};

class WebpackCLIPlugin {
constructor(options) {
this.options = options;

this.isWatch = false;
}

async apply(compiler) {
const compilers = compiler.compilers || [compiler];
const { progress } = this.options;

for (const compiler of compilers) {
if (this.options.progress) {
const { ProgressPlugin } = compiler.webpack || webpack;
if (progress) {
appendProgressPlugin(compiler, progress);
}

let progressPluginExists;
const logger = compiler.getInfrastructureLogger(PluginName);

if (compiler.options.plugins) {
progressPluginExists = Boolean(compiler.options.plugins.find((plugin) => plugin instanceof ProgressPlugin));
}
const resolveName = (obj) => (obj.name ? `${obj.name}: ` : '');

const done = (stats) => {
const printStats = (childCompiler, childStats) => {
const statusOptions = (value) => ({
version: value,
timings: value,
});
const statsOptions = {
...getStatsOptions(childCompiler),
...statusOptions(false),
};

const statsString = childStats.toString(statsOptions);

if (!progressPluginExists) {
if (typeof this.options.progress === 'string' && this.options.progress !== 'profile') {
logger.error(
`'${this.options.progress}' is an invalid value for the --progress option. Only 'profile' is allowed.`,
);
process.exit(2);
if (statsString.length) {
if (childStats.hasErrors()) {
logger.error(statsString);
} else if (childStats.hasWarnings()) {
logger.warn(statsString);
} else {
logger.info(statsString);
}
}

const isProfile = this.options.progress === 'profile';
const status = childStats.toString({ preset: 'none', ...statusOptions(true) });

new ProgressPlugin({ profile: isProfile }).apply(compiler);
if (childStats.hasErrors()) {
logger.error(status);
} else if (childStats.hasWarnings()) {
logger.warn(status);
} else {
logger.info(status);
}
}
}

const compilationName = (compilation) => (compilation.name ? ` ${compilation.name}` : '');
if (this.isWatch) {
logger.info(resolveName(childCompiler) + 'watching files for updates...');
}
};

compiler.hooks.watchRun.tap(PluginName, (compilation) => {
const { bail, watch } = compilation.options;
if (bail && watch) {
logger.warn('You are using "bail" with "watch". "bail" will still exit webpack when the first error is found.');
if (compiler.compilers) {
compiler.compilers.forEach((compilerFromMultiCompileMode, index) => {
printStats(compilerFromMultiCompileMode, stats.stats[index]);
});
} else {
printStats(compiler, stats);
}
};

logger.success(`Compilation${compilationName(compilation)} starting...`);
compiler.hooks.run.tap(PluginName, (compilation) => {
logger.info(resolveName(compilation) + 'compilation starting...');
});
compiler.hooks.watchRun.tap(PluginName, (compilation) => {
logger.info(resolveName(compilation) + 'compilation starting...');

compiler.hooks.done.tap(PluginName, (compilation) => {
logger.success(`Compilation${compilationName(compilation)} finished`);

process.nextTick(() => {
if (compiler.watchMode) {
logger.success('watching files for updates...');
}
});
if (compilation.options.bail) {
logger.warn('you are using "bail" with "watch". "bail" will still exit webpack when the first error is found.');
}
this.isWatch = true;
});
compiler.hooks.done.tap(PluginName, done);
}
}

Expand Down
22 changes: 22 additions & 0 deletions packages/webpack-cli/lib/utils/stats-options.js
@@ -0,0 +1,22 @@
const { packageExists } = require('./package-exists');
const webpack = packageExists('webpack') ? require('webpack') : undefined;
const { options: coloretteOptions } = require('colorette');

const getStatsOptions = (compiler) => {
let options = compiler.options ? compiler.options.stats : undefined;

// TODO remove after drop webpack@4
if (webpack.Stats && webpack.Stats.presetToOptions) {
if (!options) {
options = {};
} else if (typeof options === 'boolean' || typeof options === 'string') {
options = webpack.Stats.presetToOptions(options);
}
}

options.colors = typeof options.colors !== 'undefined' ? options.colors : coloretteOptions.enabled;

return options;
};

module.exports = { getStatsOptions };
57 changes: 21 additions & 36 deletions packages/webpack-cli/lib/webpack-cli.js
Expand Up @@ -7,8 +7,8 @@ const argParser = require('./utils/arg-parser');
const { outputStrategy } = require('./utils/merge-strategies');
const assignFlagDefaults = require('./utils/flag-defaults');
const { writeFileSync } = require('fs');
const { options: coloretteOptions } = require('colorette');
const WebpackCLIPlugin = require('./plugins/WebpackCLIPlugin');
const { getStatsOptions } = require('./utils/stats-options');

// CLI arg resolvers
const handleConfigResolution = require('./groups/ConfigGroup');
Expand Down Expand Up @@ -195,9 +195,9 @@ class WebpackCLI {
let options = this.compilerConfiguration;
let outputOptions = this.outputConfiguration;

const isRawOutput = typeof outputOptions.json === 'undefined';
const isJsonOutput = typeof outputOptions.json !== 'undefined';

if (isRawOutput) {
if (!isJsonOutput) {
const webpackCLIPlugin = new WebpackCLIPlugin({
progress: outputOptions.progress,
});
Expand Down Expand Up @@ -225,43 +225,28 @@ class WebpackCLI {
process.exitCode = 1;
}

const getStatsOptions = (stats) => {
// TODO remove after drop webpack@4
if (webpack.Stats && webpack.Stats.presetToOptions) {
if (!stats) {
stats = {};
} else if (typeof stats === 'boolean' || typeof stats === 'string') {
stats = webpack.Stats.presetToOptions(stats);
}
}

stats.colors = typeof stats.colors !== 'undefined' ? stats.colors : coloretteOptions.enabled;

return stats;
};

const getStatsOptionsFromCompiler = (compiler) => getStatsOptions(compiler.options ? compiler.options.stats : undefined);
if (isJsonOutput) {
process.nextTick(() => {
const statsOptions = compiler.compilers
? { children: compiler.compilers.map(getStatsOptions) }
: getStatsOptions(compiler);

const foundStats = compiler.compilers
? { children: compiler.compilers.map(getStatsOptionsFromCompiler) }
: getStatsOptionsFromCompiler(compiler);
const json = JSON.stringify(stats.toJson(statsOptions), null, 2);

if (outputOptions.json === true) {
process.stdout.write(JSON.stringify(stats.toJson(foundStats), null, 2) + '\n');
} else if (typeof outputOptions.json === 'string') {
const JSONStats = JSON.stringify(stats.toJson(foundStats), null, 2);
if (typeof outputOptions.json === 'string') {
try {
writeFileSync(outputOptions.json, json);

try {
writeFileSync(outputOptions.json, JSONStats);
logger.info(`stats are successfully stored as json to ${outputOptions.json}`);
} catch (error) {
logger.error(error);

logger.success(`stats are successfully stored as json to ${outputOptions.json}`);
} catch (error) {
logger.error(error);

process.exit(2);
}
} else {
logger.raw(`${stats.toString(foundStats)}`);
process.exit(2);
}
} else {
process.stdout.write(json + '\n');
}
});
}
};

Expand Down

0 comments on commit 6c02ec7

Please sign in to comment.