Skip to content

feat(@angular/cli): Allow ability to set budget sizes for your bundles #7458

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

Closed
wants to merge 2 commits into from
Closed
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
21 changes: 21 additions & 0 deletions packages/@angular/cli/lib/config/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,27 @@
"description": "Name and corresponding file for environment config.",
"type": "object",
"additionalProperties": true
},
"budgets": {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With this scheme, how do I specify the error/warning levels? How do I specify my budget for initial vs total?

"description": "Defines the budget allotments for bundles.",
"type": "array",
"items": {
"type": "object",
"properties": {
"budget": {
"type": "number"
},
"type": {
"type": "string"
},
"unit": {
"type": "string"
},
"severity": {
"type": "string"
}
}
}
}
},
"additionalProperties": false
Expand Down
37 changes: 32 additions & 5 deletions packages/@angular/cli/tasks/build.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
import * as fs from 'fs-extra';
import * as path from 'path';
import * as webpack from 'webpack';
import { red, yellow } from 'chalk';

import { getAppFromConfig } from '../utilities/app-utils';
import { BuildTaskOptions } from '../commands/build';
import { NgCliWebpackConfig } from '../models/webpack-config';
import { getWebpackStatsConfig } from '../models/webpack-configs/utils';
import { CliConfig } from '../models/config';
import { statsToString, statsWarningsToString, statsErrorsToString } from '../utilities/stats';
import {
statsToString,
statsWarningsToString,
statsErrorsToString,
evaluateBudgets,
BudgetResult
} from '../utilities/stats';

const Task = require('../ember-cli/lib/models/task');
const SilentError = require('silent-error');
Expand All @@ -17,9 +24,9 @@ export default Task.extend({
run: function (runTaskOptions: BuildTaskOptions) {
const config = CliConfig.fromProject().config;

const app = getAppFromConfig(runTaskOptions.app);
const appConfig = getAppFromConfig(runTaskOptions.app);

const outputPath = runTaskOptions.outputPath || app.outDir;
const outputPath = runTaskOptions.outputPath || appConfig.outDir;
if (this.project.root === path.resolve(outputPath)) {
throw new SilentError('Output path MUST not be project root directory!');
}
Expand All @@ -30,7 +37,7 @@ export default Task.extend({
fs.removeSync(path.resolve(this.project.root, outputPath));
}

const webpackConfig = new NgCliWebpackConfig(runTaskOptions, app).buildConfig();
const webpackConfig = new NgCliWebpackConfig(runTaskOptions, appConfig).buildConfig();
const webpackCompiler = webpack(webpackConfig);
const statsConfig = getWebpackStatsConfig(runTaskOptions.verbose);

Expand All @@ -41,10 +48,30 @@ export default Task.extend({
}

const json = stats.toJson('verbose');

let budgetResults: BudgetResult[];
if (runTaskOptions.target === 'production' && !!appConfig.budgets) {
budgetResults = evaluateBudgets(json, appConfig.budgets);
}

if (runTaskOptions.verbose) {
this.ui.writeLine(stats.toString(statsConfig));
} else {
this.ui.writeLine(statsToString(json, statsConfig));
const bundleBudgetResults = budgetResults.filter(br => br.type === 'bundle');
this.ui.writeLine(statsToString(json, statsConfig, bundleBudgetResults));
}


const initialBudgetResults = budgetResults.filter(br => br.type === 'initial');
if (initialBudgetResults.length > 0) {
const prefix = initialBudgetResults.every(b => b.result === 'Warning')
? 'Warning' : 'Error';
const color = prefix === 'Warning' ? yellow : red;
this.ui.writeLine(color(`${prefix}: Initial budget size exceeded.`));
}

if (budgetResults.filter(br => br.result === 'Error').length > 0) {
reject('Bundle budget exceeded');
}

if (stats.hasWarnings()) {
Expand Down
90 changes: 86 additions & 4 deletions packages/@angular/cli/utilities/stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,35 @@ import { bold, green, red, reset, white, yellow } from 'chalk';
import { stripIndents } from 'common-tags';


export type BudgetType = 'bundle' | 'initial';

export interface Budget {
type: BudgetType;
budget: number;
unit: SizeUnit;
severity: 'Warning' | 'Error';
}

export type SizeUnit = 'bytes' | 'kB' | 'MB' | 'GB';

const sizeUnits = ['bytes', 'kB', 'MB', 'GB'];

function _formatSize(size: number): string {
if (size <= 0) {
return '0 bytes';
}

const abbreviations = ['bytes', 'kB', 'MB', 'GB'];
const index = Math.floor(Math.log(size) / Math.log(1000));

return `${+(size / Math.pow(1000, index)).toPrecision(3)} ${abbreviations[index]}`;
return `${+(size / Math.pow(1000, index)).toPrecision(3)} ${sizeUnits[index]}`;
}

function _getSize(size: number, unit: SizeUnit): number {
const unitMultiplier = sizeUnits.indexOf(unit);
return size / Math.pow(1000, unitMultiplier);
}

export function statsToString(json: any, statsConfig: any) {
export function statsToString(json: any, statsConfig: any, budgetResults: BudgetResult[] = []) {
const colors = statsConfig.colors;
const rs = (x: string) => colors ? reset(x) : x;
const w = (x: string) => colors ? bold(white(x)) : x;
Expand All @@ -36,7 +52,22 @@ export function statsToString(json: any, statsConfig: any) {
.map(f => f && chunk[f] ? g(` [${f}]`) : '')
.join('');

return `chunk {${y(chunk.id)}} ${g(files)}${names}${size}${parents} ${initial}${flags}`;
let msg = `chunk {${y(chunk.id)}} ${g(files)}${names}${size}${parents} ${initial}${flags}`;

const chunkWarnings = budgetResults
.filter(bbr => bbr.id === chunk.id && bbr.result === 'Warning');
const chunkErrors = budgetResults
.filter(bbr => bbr.id === chunk.id && bbr.result === 'Error');

const chunkBudgetResults = chunkErrors.length > 0 ? chunkErrors : chunkWarnings;

chunkBudgetResults.forEach(bbr => {
const color = bbr.result === 'Warning' ? yellow : red;
const budgetMessage = `Bundle budget size exceeded (${bbr.budget} ${bbr.unit})`;
msg += `\n${color(budgetMessage)}`;
});

return msg;
}).join('\n')}
`);
}
Expand All @@ -56,3 +87,54 @@ export function statsErrorsToString(json: any, statsConfig: any) {

return rs('\n' + json.errors.map((error: any) => r(`ERROR in ${error}`)).join('\n'));
}

export interface BudgetResult {
result: 'Error' | 'Warning';
type: BudgetType;
budget: number;
unit: SizeUnit;
id?: number;
}

export function evaluateBudgets(stats: any, budgets: Budget[]): BudgetResult[] {
const results: BudgetResult[] = [];

const bundleBudgets = budgets.filter(b => b.type === 'bundle');
let initialSize = 0;

stats.chunks.forEach((chunk: any) => {
const asset = stats.assets.filter((x: any) => x.name == chunk.files[0])[0];
const chunkSize = asset.size;

initialSize += chunk.initial ? chunkSize : 0;

if (!chunk.initial) {
bundleBudgets.forEach(budget => {
const chunkSizeInUnit = _getSize(chunkSize, budget.unit);
if (chunkSizeInUnit > budget.budget) {
results.push({
id: chunk.id,
type: 'bundle',
result: budget.severity,
budget: budget.budget,
unit: budget.unit
});
}
});
}
});

budgets.filter(b => b.type === 'initial').forEach(budget => {
const initialSizeInUnit = _getSize(initialSize, budget.unit);
if (initialSizeInUnit > budget.budget) {
results.push({
type: 'initial',
result: budget.severity,
budget: budget.budget,
unit: budget.unit
});
}
});

return results;
}
28 changes: 28 additions & 0 deletions tests/e2e/tests/build/budgets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import {ng} from '../../utils/process';
import {updateJsonFile} from '../../utils/project';
import {expectToFail} from '../../utils/utils';


export default function() {
return Promise.resolve()
.then(() => updateJsonFile('.angular-cli.json', configJson => {
const app = configJson['apps'][0];
app['budgets'] = [{
type: 'initial',
budget: 1,
unit: 'kB',
severity: 'Warning'
}];
}))
.then(() => ng('build', '--prod'))
.then(() => updateJsonFile('.angular-cli.json', configJson => {
const app = configJson['apps'][0];
app['budgets'] = [{
type: 'initial',
budget: 1,
unit: 'kB',
severity: 'Error'
}];
}))
.then(() => expectToFail(() => ng('build', '--prod')));
}