Skip to content

feat(@ngtools/webpack): show warning when large CSS are included in c… #15093

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 1 commit 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
38 changes: 34 additions & 4 deletions packages/ngtools/webpack/src/angular_compiler_plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ import {
MESSAGE_KIND,
UpdateMessage,
} from './type_checker_messages';
import { flattenArray, forwardSlashPath, workaroundResolve } from './utils';
import { flattenArray, formatSize, forwardSlashPath, workaroundResolve } from './utils';
import {
VirtualFileSystemDecorator,
VirtualWatchFileSystemDecorator,
Expand All @@ -85,6 +85,12 @@ import { WebpackInputHost } from './webpack-input-host';

const treeKill = require('tree-kill');

/**
* The recommended maximum size of components styles in bytes.
*/
const stylesSizeLimit = 70 * 1024;
const formattedStylesSizeLimit = formatSize(stylesSizeLimit);

export class AngularCompilerPlugin {
private _options: AngularCompilerPluginOptions;

Expand Down Expand Up @@ -131,6 +137,8 @@ export class AngularCompilerPlugin {

private _mainFields: string[] = [];

private _stylesResources = new Set<string>();

constructor(options: AngularCompilerPluginOptions) {
this._options = Object.assign({}, options);
this._setupOptions(this._options);
Expand Down Expand Up @@ -788,6 +796,24 @@ export class AngularCompilerPlugin {
compiler.hooks.afterEmit.tap('angular-compiler', compilation => {
// tslint:disable-next-line:no-any
(compilation as any)._ngToolsWebpackPluginInstance = null;

// CSS size checks
const stylesSizeWarning: string[] = [];
this._stylesResources.forEach(fileName => {
const styleModule = compilation.modules.find(
x => typeof x.resource === 'string' && x.resource.replace(/\.shim\.ngstyle\.js$/, '') === fileName
);
const styleModuleSize = styleModule && styleModule.size();
if (styleModuleSize && styleModuleSize > stylesSizeLimit) {
stylesSizeWarning.push(
`${fileName} (${formatSize(styleModuleSize)}) component style size exceeds the recommended limit (${formattedStylesSizeLimit}).`,
);
}
})

if (stylesSizeWarning.length) {
compilation.warnings.push(...stylesSizeWarning);
}
});
compiler.hooks.done.tap('angular-compiler', () => {
this._donePromise = null;
Expand Down Expand Up @@ -1176,16 +1202,20 @@ export class AngularCompilerPlugin {
})
.filter(x => x);

const resourceImports = findResources(sourceFile)
.map(resourcePath => resolve(dirname(resolvedFileName), normalize(resourcePath)));
const { templates, styles } = findResources(sourceFile);
const templatesImports = templates.map(resourcePath => resolve(dirname(resolvedFileName), normalize(resourcePath)));
const stylesImports = styles.map(resourcePath => resolve(dirname(resolvedFileName), normalize(resourcePath)));

// These paths are meant to be used by the loader so we must denormalize them.
const uniqueDependencies = new Set([
...esImports,
...resourceImports,
...stylesImports,
...templatesImports,
...this.getResourceDependencies(this._compilerHost.denormalizePath(resolvedFileName)),
].map((p) => p && this._compilerHost.denormalizePath(p)));

stylesImports.forEach(f => this._stylesResources.add(this._compilerHost.denormalizePath(f)));

return [...uniqueDependencies]
.filter(x => !!x) as string[];
}
Expand Down
11 changes: 6 additions & 5 deletions packages/ngtools/webpack/src/transformers/find_resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ import * as ts from 'typescript';
import { collectDeepNodes } from './ast_helpers';
import { getResourceUrl } from './replace_resources';

export function findResources(sourceFile: ts.SourceFile): string[] {
const resources: string[] = [];
export function findResources(sourceFile: ts.SourceFile): { templates: string[]; styles: string[]} {
const decorators = collectDeepNodes<ts.Decorator>(sourceFile, ts.SyntaxKind.Decorator);
const templates: string[] = [];
const styles: string[] = [];

for (const node of decorators) {
if (!ts.isCallExpression(node.expression)) {
Expand All @@ -38,7 +39,7 @@ export function findResources(sourceFile: ts.SourceFile): string[] {
const url = getResourceUrl(node.initializer);

if (url) {
resources.push(url);
templates.push(url);
}
break;

Expand All @@ -51,7 +52,7 @@ export function findResources(sourceFile: ts.SourceFile): string[] {
const url = getResourceUrl(node);

if (url) {
resources.push(url);
styles.push(url);
}

return node;
Expand All @@ -64,5 +65,5 @@ export function findResources(sourceFile: ts.SourceFile): string[] {
);
}

return resources;
return { templates, styles };
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,13 @@ describe('@ngtools/webpack transformers', () => {
`;

const result = findResources(ts.createSourceFile('temp.ts', input, ts.ScriptTarget.ES2015));
expect(result).toEqual([
'./app.component.html',
expect(result.styles).toEqual([
'./app.component.css',
'./app.component.2.css',
]);
expect(result.templates).toEqual([
'./app.component.html',
]);
});

it('should not return resources if they are not in decorator', () => {
Expand All @@ -43,7 +45,8 @@ describe('@ngtools/webpack transformers', () => {
`;

const result = findResources(ts.createSourceFile('temp.ts', input, ts.ScriptTarget.ES2015));
expect(result).toEqual([]);
expect(result.styles).toEqual([]);
expect(result.templates).toEqual([]);
});
});
});
10 changes: 10 additions & 0 deletions packages/ngtools/webpack/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,13 @@ export function flattenArray<T>(value: Array<T | T[]>): T[] {
export function forwardSlashPath(path: string) {
return path.replace(/\\/g, '/');
}

export 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(1024));

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