Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve logger #392

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@
"tslint": "5.18.0"
},
"dependencies": {
"@dojo/webpack-contrib": "8.0.0-alpha.1",
"@dojo/webpack-contrib": "file:~/Projects/opensource/webpack-contrib/dist/release/dojo-webpack-contrib-8.0.0-pre.tgz",
"@typescript-eslint/eslint-plugin": "2.34.0",
"@typescript-eslint/parser": "2.34.0",
"caniuse-lite": "1.0.30000973",
Expand Down
8 changes: 0 additions & 8 deletions src/dist.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import BuildTimeRender from '@dojo/webpack-contrib/build-time-render/BuildTimeRender';
import ExternalLoaderPlugin from '@dojo/webpack-contrib/external-loader-plugin/ExternalLoaderPlugin';
import BundleAnalyzerPlugin from '@dojo/webpack-contrib/webpack-bundle-analyzer/BundleAnalyzerPlugin';
import ServiceWorkerPlugin, {
ServiceWorkerOptions
} from '@dojo/webpack-contrib/service-worker-plugin/ServiceWorkerPlugin';
Expand Down Expand Up @@ -84,13 +83,6 @@ function webpackConfig(args: any): webpack.Configuration {
config.plugins = [
...plugins!,
assetsDirExists && new CopyWebpackPlugin([{ from: assetsDir, to: path.join(outputPath, 'assets') }]),
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
generateStatsFile: true,
reportFilename: '../info/report.html',
statsFilename: '../info/stats.json'
}),
new HtmlWebpackPlugin({
base,
inject: true,
Expand Down
94 changes: 52 additions & 42 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import * as fs from 'fs';
import * as path from 'path';
import * as logUpdate from 'log-update';
import * as logSymbols from 'log-symbols';
import * as gzipSize from 'gzip-size';
import * as typescript from 'typescript';
import * as jsonFile from 'jsonfile';
import analyzeBundles from '@dojo/webpack-contrib/webpack-bundle-analyzer/AnalyzeBundles';
import { findLargestPackage } from '@dojo/webpack-contrib/webpack-bundle-analyzer/parseUtils';
import chalk from 'chalk';

const pkgDir = require('pkg-dir');
Expand All @@ -15,58 +15,70 @@ const version = jsonFile.readFileSync(path.join(pkgDir.sync(__dirname), 'package
export default function logger(stats: any, config: any, runningMessage: string = '', args: any = {}): boolean {
const singleConfig = Array.isArray(config) ? config[0] : config;
const outputPath = singleConfig.output.path;
const manifestPath = path.join(outputPath, 'manifest.json');
let assets: undefined | string[];
const loggerStats = stats.toJson({ warningsFilter });
let chunks: undefined | string[];
if (fs.existsSync(manifestPath)) {
const manifestContent = JSON.parse(fs.readFileSync(path.join(outputPath, 'manifest.json'), 'utf8'));
assets = Object.keys(manifestContent).map((item) => {
const assetName = manifestContent[item];
const filePath = path.join(outputPath, assetName);
if (fs.existsSync(filePath)) {
if (args.mode === 'dev' || args.mode === 'test') {
return `${assetName}`;
} else {
const fileStats = fs.statSync(filePath);
const size = (fileStats.size / 1000).toFixed(2);
if (/\.(gz|br)$/.test(filePath)) {
return `${assetName} ${chalk.blue(`(${size}kb)`)}`;

let chunkMap: { [chunk: string]: any };
const excludeChunks = /(^bootstrap$)|(^runtime\/)/;
if (args.mode === 'dist') {
chunkMap = analyzeBundles(stats, config, {
analyzerMode: 'static',
openAnalyzer: false,
generateStatsFile: true,
reportFilename: '../info/report.html',
statsFilename: '../info/stats.json',
excludeBundles: '(^bootstrap\\.)|(^runtime/)'
});
}
chunks = (Array.isArray(config)
? loggerStats.children.reduce((chunks: any[], current: any) => [...chunks, ...current.chunks], [])
: loggerStats.chunks
)
.filter((chunk: any) => !excludeChunks.test(chunk.names[0] || ''))
.map((chunk: any) => {
const chunkName: string = chunk.names[0];
if (!chunkMap) {
return chunkName;
} else {
const chunkStats = chunkMap[chunkName];
const size = ((chunkStats && (chunkStats.parsedSize || chunkStats.statSize)) || 0) / 1000;
const gzipSize = ((chunkStats && chunkStats.gzipSize) || 0) / 1000;

const chunkInfo = `${chunkName} ${chalk.yellow(`(${size}kB)`)}${
gzipSize ? ` / ${chalk.blue(`(${gzipSize}kB gz)`)}` : ''
}`;

if (size > 250) {
const largestPackage = findLargestPackage(chunkStats);
if (largestPackage) {
return `${chunkInfo}\nLargest dependency is ${largestPackage.name} ${chalk.yellow(
`(${largestPackage.size / 1000}kB)`
)}`;
}
// Calculate and report size when gzipped
const content = fs.readFileSync(filePath, 'utf8');
const compressedSize = (gzipSize.sync(content) / 1000).toFixed(2);
const assetInfo = `${assetName} ${chalk.yellow(`(${size}kb)`)}`;
return `${assetInfo} / ${chalk.blue(`(${compressedSize}kb gz)`)}`;
}
return chunkInfo;
}
return '';
});

chunks = (Array.isArray(config)
? stats.children.reduce((chunks: any[], current: any) => [...chunks, ...current.chunks], [])
: stats.chunks
).map((chunk: any) => `${chunk.names[0]}`);
}

let errors = '';
let warnings = '';
let chunkAndAssetLog = '';
let signOff = chalk.green('The build completed successfully.');

if (stats.warnings.length) {
if (loggerStats.warnings.length) {
signOff = chalk.yellow('The build completed with warnings.');
warnings = `
${chalk.yellow('warnings:')}${chalk.gray(
stats.warnings.reduce((warnings: string, warning: string) => `${warnings}\n${stripAnsi(warning)}`, '')
loggerStats.warnings.reduce((warnings: string, warning: string) => `${warnings}\n${stripAnsi(warning)}`, '')
)}
`;
}

if (stats.errors.length) {
if (loggerStats.errors.length) {
signOff = chalk.red('The build completed with errors.');
errors = `
${chalk.yellow('errors:')}${chalk.red(
stats.errors.reduce((errors: string, error: string) => `${errors}\n${stripAnsi(error)}`, '')
loggerStats.errors.reduce((errors: string, error: string) => `${errors}\n${stripAnsi(error)}`, '')
)}
`;
}
Expand All @@ -80,18 +92,12 @@ ${chalk.yellow('errors:')}${chalk.red(
${columns(chunks)}`;
}

if (assets) {
chunkAndAssetLog = `${chunkAndAssetLog}
${chalk.yellow('assets:')}
${columns(assets)}`;
}

logUpdate(`
${logSymbols.info} cli-build-app: ${version}
${logSymbols.info} typescript: ${typescript.version}
${logSymbols.success} hash: ${stats.hash}
${logSymbols.error} errors: ${stats.errors.length}
${logSymbols.warning} warnings: ${stats.warnings.length}
${logSymbols.success} hash: ${loggerStats.hash}
${logSymbols.error} errors: ${loggerStats.errors.length}
${logSymbols.warning} warnings: ${loggerStats.warnings.length}
${errors}${warnings}
${chunkAndAssetLog}
${chalk.yellow(`output at: ${chalk.cyan(chalk.underline(`file:///${outputPath}`))}`)}
Expand All @@ -100,3 +106,7 @@ ${signOff}
`);
return !!errors;
}

function warningsFilter(warning: string) {
return warning.includes('[mini-css-extract-plugin]\nConflicting order between');
}
8 changes: 2 additions & 6 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ function build(configs: webpack.Configuration[], args: any) {
}
if (stats) {
const runningMessage = args.serve ? `Listening on port ${args.port}...` : '';
const hasErrors = logger(stats.toJson({ warningsFilter }), configs, runningMessage, args);
const hasErrors = logger(stats, configs, runningMessage, args);
if (hasErrors) {
reject({});
return;
Expand Down Expand Up @@ -143,7 +143,7 @@ function fileWatch(configs: webpack.Configuration[], args: any, shouldResolve =
args.port
}\nPlease note the serve option is not intended to be used to serve applications in production.`
: 'watching...';
logger(stats.toJson({ warningsFilter }), configs, runningMessage, args);
logger(stats, configs, runningMessage, args);
}
if (shouldResolve) {
resolve(compiler);
Expand Down Expand Up @@ -286,10 +286,6 @@ async function serve(configs: webpack.Configuration[], args: any) {
});
}

function warningsFilter(warning: string) {
return warning.includes('[mini-css-extract-plugin]\nConflicting order between');
}

const command: Command = {
group: 'build',
name: 'app',
Expand Down
Loading