Created
August 15, 2017 00:20
-
-
Save addyosmani/4bd8d89fa447dd38a02c92c022b6cbca to your computer and use it in GitHub Desktop.
Detecting unminified code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://hg.mozilla.org/mozilla-central/rev/2f9043292e63 | |
// Used to detect minification for automatic pretty printing | |
const SAMPLE_SIZE = 30; // no of lines | |
const INDENT_COUNT_THRESHOLD = 20; // percentage | |
function isMinified (str) { | |
let isMinified; | |
let lineEndIndex = 0; | |
let lineStartIndex = 0; | |
let lines = 0; | |
let indentCount = 0; | |
// Strip comments. | |
str = str.replace(/\/\*[\S\s]*?\*\/|\/\/(.+|\n)/g, ""); | |
while (lines++ < SAMPLE_SIZE) { | |
lineEndIndex = str.indexOf("\n", lineStartIndex); | |
if (lineEndIndex == -1) { | |
break; | |
} | |
if (/^\s+/.test(str.slice(lineStartIndex, lineEndIndex))) { | |
indentCount++; | |
} | |
lineStartIndex = lineEndIndex + 1; | |
} | |
isMinified = ((indentCount / lines ) * 100) < INDENT_COUNT_THRESHOLD; | |
return isMinified; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FYI: The one from Google DevTools is much faster:
https://github.com/ChromeDevTools/devtools-frontend/blob/main/front_end/models/text_utils/TextUtils.ts#L336
small not minified file (5kb)
angular.min.js (173Kb)
angular.js (1.3Mb)
But not as reliable, when there is
eval()
usage with unminified code inside FF version says it's not minified (which is truth) while the one from google dev tools says it is. But that's rather an edge case scenario