Skip to content

Beautifying unminified code

Denis Porfiryev edited this page May 21, 2020 · 7 revisions

Beautifying unminified code

Webpack minifies javascript code to make it smaller and faster to parse. During that process minification plugin renames most of variables and functions to 1-2 character length names, removes comments and whitespaces.

Besides that it performs some more optimizations which sometimes change expressions order.

When creating mods its important to keep them readable and understandable, I'll describe some transformations which may help with this.

!0, !1

Expressions !0 and !1 are short form of true and false respectively.

Comma

Expressions like

a, b, c

are executed consequentially, the result is the latest subexpression. We can split such expressions into smaller separate ones

constructor(...e) {
    super(...e), defineProperty(this, "state", {
        disabled: !0
    }), defineProperty(this, "enable", () => this.setState({
        disabled: this.props.disabled || !1
    }))
}

After splitting:

constructor(...e) {
    super(...e)
    
    defineProperty(this, "state", { disabled: true })
    
    defineProperty(this, "enable",
        () => this.setState({ disabled: this.props.disabled || false }))
}

When an expression is used as a condition expression in if, initialization expression in for, as a return value etc, all subexpressions except the latest one may be moved out:

return e[n] = 7, r.split("").forEach((function (e) {
    t[e] = e
})), 7 != u({}, e)[n] || Object.keys(u({}, t)).join("") != r

becames

e[n] = 7

r.split("").forEach((function (e) { t[e] = e }))

return 7 != u({}, e)[n]  ||  Object.keys(u({}, t)).join("") != r

&& and ||

Large amount of && and || in the minified code are optimized conditional operators.

a && b && c      //if (a && b) { c }
a && b && c || d //if (a && b) { c } else { d }
a || b           //if (!a) { b }

But don't do (or at least be careful with) such transformatoins when the result of such expression is used (as a condition expression, return value, ...).

Clone this wiki locally