Skip to content

Commit

Permalink
[v1.0.1] Grouping log messages and fixing few issue noticed
Browse files Browse the repository at this point in the history
* Fixing few issue noticed and grouping the log messages

* Modifying null check condition
  • Loading branch information
prate3k committed Oct 18, 2019
1 parent 6bee80a commit 325ce9b
Show file tree
Hide file tree
Showing 7 changed files with 121 additions and 95 deletions.
14 changes: 6 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,9 @@
# chunk-restriction-plugin
> Webpack plugin to help you monitor your chunk size.

![Incorrect String](https://i.ibb.co/DMCShNL/Screen-Shot-2019-10-15-at-2-25-02-PM.png)

![Error log](https://i.ibb.co/kczW9D9/Screen-Shot-2019-10-15-at-1-04-21-PM.png)

![Warning log](https://i.ibb.co/zbFNsYW/Screen-Shot-2019-10-15-at-11-08-53-AM.png)

##### Install the package :
```bash
npm install chunk-restriction-plugin --save
npm install chunk-restriction-plugin --save-dev
```

##### Usage :
Expand All @@ -35,6 +28,11 @@ const webpackConfig = {
}
```

###### Log Screenshots :
![Error Log](./screenshots/error.png)

![Warning log](./screenshots/warning.png)

#### Options :
Properties are define like this :
> type        |        mandatory        |        defaultValue
Expand Down
2 changes: 1 addition & 1 deletion 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
@@ -1,6 +1,6 @@
{
"name": "chunk-restriction-plugin",
"version": "1.0.0",
"version": "1.0.1",
"description": "Chunk restriction plugin for webpack",
"main": "dist/cjs.js",
"engines": {
Expand Down
Binary file added screenshots/error.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added screenshots/warning.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
115 changes: 48 additions & 67 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,33 @@
import validateOptions from 'schema-utils';

import {
formatSize,
logMessage,
hasOwnProperty,
buildChunkStatsJson,
parseHumanReadableSizeToByte,
replaceMessagePlaceholder
} from './utils';
import { hasOwnProperty, buildChunkStatsJson, performCheck } from './utils';

import schema from './options.json';

export class LogMessage {
constructor() {
this.warnings = '';
this.errors = '';
}
pushMessage(type, msg) {
if (type === 'warning') {
this.warnings += `- ${msg}\n\n`;
} else {
this.errors += `- ${msg}\n\n`;
}
}
logMessage(compilation) {
if (this.warnings && this.warnings.length > 0) {
compilation.warnings.push(
`Chunk Restriction Plugin => \n\n${this.warnings}`
);
}
if (this.errors && this.errors.length > 0) {
compilation.errors.push(`Chunk Restriction Plugin => \n\n${this.errors}`);
}
}
}

class ChunkRestrictionPlugin {
constructor(opts = {}) {
this.opts = opts || {};
Expand All @@ -34,69 +51,33 @@ class ChunkRestrictionPlugin {
}

const manifest = buildChunkStatsJson(compilation, assetsMeta);
const messages = new LogMessage();
const restrictionParams = [
{ property: 'jsSize', fileExt: 'js' },
{ property: 'cssSize', fileExt: 'css' }
];
restrictions.forEach((restriction) => {
if (typeof restriction.jsSize === 'string' && !!restriction.jsSize) {
const jsNumberParser = parseHumanReadableSizeToByte(restriction.jsSize);
const jsSize = jsNumberParser.parsedBytes;
if (jsNumberParser.invalid) {
logMessage('error', jsNumberParser.message, compilation);
}
if (
!jsNumberParser.invalid &&
typeof jsSize === 'number' &&
jsSize < manifest[restriction.chunkName].js.size
) {
logMessage(
restriction.logType || defaultLogType,
replaceMessagePlaceholder(
{
chunkName: restriction.chunkName,
ext: 'js',
totalSize: formatSize(manifest[restriction.chunkName].js.size),
difference: formatSize(
manifest[restriction.chunkName].js.size - jsSize
),
restriction: formatSize(jsSize)
},
restriction.logMessageFormat || defaultLogMessageFormat
),
compilation
);
}
}

if (typeof restriction.cssSize === 'string' && !!restriction.cssSize) {
const cssNumberParser = parseHumanReadableSizeToByte(
restriction.cssSize
const severity = restriction.logType || defaultLogType;
if (!hasOwnProperty(manifest, restriction.chunkName)) {
messages.pushMessage(
severity,
`[Missing] No chunk with name : "${restriction.chunkName}" present, Either remove the restriction or check if correct chunk name is specified.`
);
const cssSize = cssNumberParser.parsedBytes;
if (cssNumberParser.invalid) {
logMessage('error', cssNumberParser.message, compilation);
}
if (
!cssNumberParser.invalid &&
typeof cssSize === 'number' &&
cssSize < manifest[restriction.chunkName].css.size
) {
logMessage(
restriction.logType || defaultLogType,
replaceMessagePlaceholder(
{
chunkName: restriction.chunkName,
ext: 'css',
totalSize: formatSize(manifest[restriction.chunkName].css.size),
difference: formatSize(
manifest[restriction.chunkName].css.size - cssSize
),
restriction: formatSize(cssSize)
},
restriction.logMessageFormat || defaultLogMessageFormat
),
compilation
);
}
return;
}
restrictionParams.forEach((restrictionParam) => {
performCheck({
property: restrictionParam.property,
fileExt: restrictionParam.fileExt,
manifest,
restriction,
severity,
messages,
msgFormat: restriction.logMessageFormat || defaultLogMessageFormat
});
});
});
messages.logMessage(compilation);
}

apply(compiler) {
Expand Down
83 changes: 65 additions & 18 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,6 @@ export function formatSize(size) {
return `${+(size / 1024 ** index).toPrecision(3)} ${abbreviations[index]}`;
}

export function logMessage(type, msg, compilation) {
if (type === 'warning') {
compilation.warnings.push(msg);
} else {
compilation.errors.push(msg);
}
}

export function hasOwnProperty(object, property) {
return Object.prototype.hasOwnProperty.call(object, property);
}
Expand Down Expand Up @@ -68,19 +60,18 @@ export function buildChunkStatsJson(compilation, assetsMeta) {
return chunkStats;
}

const regex = /([.0-9]+)[ ]?(Byte|Bytes|KiB|KB|MB|GB)/i;
export function parseHumanReadableSizeToByte(text) {
const regex = /^([.0-9]+)[ ]?(Byte|Bytes|KiB|KB|MB|GB)?$/i;
function parseHumanReadableSizeToByte(text) {
const matches = regex.exec(text);
if (matches == null) {
return {
message: `Incorrect string specified : ${text}, Please check. Supported format {Byte, Bytes, Kb/Kib, Mb}`,
invalid: true,
parsedBytes: 0
};
}
const [_, number, unit] = matches; // eslint-disable-line no-unused-vars
let times = 0;
switch (unit.toLowerCase()) {
switch ((unit || '').toLowerCase()) {
case 'kib':
case 'kb':
times = 1;
Expand All @@ -92,7 +83,6 @@ export function parseHumanReadableSizeToByte(text) {
break;
}
return {
message: '',
invalid: false,
parsedBytes: 1024 ** times * Number(number)
};
Expand All @@ -105,9 +95,66 @@ export function replaceMessagePlaceholder(
messageFormat
) {
return (messageFormat || DEFAULT_MSG_FORMAT)
.replace(/__CHUNK_NAME__/g, chunkName)
.replace(/__EXT__/g, ext.toUpperCase())
.replace(/__TOTAL_SIZE__/g, totalSize)
.replace(/__RESTRICTION__/g, restriction)
.replace(/__DIFFERENCE__/g, difference);
.replace('__CHUNK_NAME__', chunkName)
.replace('__EXT__', ext.toUpperCase())
.replace('__TOTAL_SIZE__', totalSize)
.replace('__RESTRICTION__', restriction)
.replace('__DIFFERENCE__', difference);
}

export function performCheck({
property,
fileExt,
manifest,
restriction,
severity,
msgFormat,
messages
}) {
if (typeof restriction[property] === 'string' && !!restriction[property]) {
const numberParser = parseHumanReadableSizeToByte(restriction[property]);
const size = numberParser.parsedBytes;
if (numberParser.invalid) {
messages.pushMessage(
'error',
`Incorrect string specified : ${restriction[property]} for chunkName "${restriction.chunkName}", Please check. Supported format {Byte, Bytes, Kb/Kib, Mb}`
);
}
if (
!numberParser.invalid &&
typeof size === 'number' &&
!hasOwnProperty(manifest[restriction.chunkName], fileExt)
) {
messages.pushMessage(
'warning',
`[Not Found] No ${fileExt.toUpperCase()} asset found for chunk name : "${
restriction.chunkName
}", hence ignoring its ${fileExt} restriction`
);
return;
}
if (
!numberParser.invalid &&
typeof size === 'number' &&
size < manifest[restriction.chunkName][fileExt].size
) {
messages.pushMessage(
severity,
replaceMessagePlaceholder(
{
chunkName: restriction.chunkName,
ext: fileExt,
totalSize: formatSize(
manifest[restriction.chunkName][fileExt].size
),
difference: formatSize(
manifest[restriction.chunkName][fileExt].size - size
),
restriction: formatSize(size)
},
msgFormat
)
);
}
}
}

0 comments on commit 325ce9b

Please sign in to comment.