A JavaScript file is written to be read by humans: explicit variable names, comments, careful indentation. The browser engine could not care less about any of it.
Minification exploits that gap. It produces an unreadable but lighter version, meant for the machine alone.
Definition
Minification is the automatic rewriting of a file to reduce its size without changing its behavior. It removes spaces and comments, shortens internal names, and drops code nothing can ever reach.
// Before: 165 characters
export function cartTotal(lines, discount = 0) {
const gross = lines.reduce((sum, line) => sum + line.price * line.quantity, 0);
return gross * (1 - discount);
}
// After: 86 characters, identical result
export function cartTotal(n,e=0){return n.reduce((n,e)=>n+e.price*e.quantity,0)*(1-e)}The parameters were renamed without consequence, since they are only visible from inside the function. The price and quantity properties stayed untouched: renaming those would break the link with objects supplied from the outside.
What a minifier allows itself, and what it refuses
- It shortens the names of local variables and parameters, invisible outside their Scope.
- It deletes comments, whitespace and optional semicolons.
- It removes dead code, such as an if branch whose condition can never be true.
- It preserves property names, string contents and anything another file might refer to by name.
Minifying is not protecting. The code stays perfectly runnable, therefore perfectly readable to anyone willing to reformat it. A secret key slipped into a file sent to the browser is a published key, minified or not.
Measure rather than assume
Minification does not act alone. The server then compresses the file before sending it, and that compression loves repetition: a verbose file compresses very well, which narrows the gap between the two versions.
The only figure that counts is therefore the size actually transferred, visible in the network tab of the developer tools. A spectacular gain on disk can amount to a couple of kilobytes over the wire, and the opposite happens too.
Frequently asked questions
Do I need to install a minification tool?
Rarely, because it already comes with the build. Vite minifies when you run vite build, Webpack does it as soon as its mode is production. Installing one separately only makes sense on a project with no bundling at all.
Why does my minified code stop working?
The usual culprit is code relying on a name the minifier is allowed to change, such as the name property of a function or the name of a class read at run time. The second suspect is a comparison of constructor names, best replaced by an explicit check.
Should code meant for Node be minified?
No, in most cases. A file read from the local disk crosses no network, and readable errors are worth far more than a few kilobytes. The exception concerns functions deployed at a hosting provider, where package weight affects startup time.