Skip to content

Commit

Permalink
JS: support different ECMAScript version to toggle optimizations, mer…
Browse files Browse the repository at this point in the history
…ge with NoNullishOperator and add NoOptionalCatchParameter, fixes #540
  • Loading branch information
tdewolff committed Nov 3, 2022
1 parent 340df5d commit a52d606
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 5 deletions.
2 changes: 1 addition & 1 deletion cmd/minify/bash_completion
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ _minify_complete() {
local cur prev flags mimes types
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
flags="-a --all --bundle --cpuprofile -l --list --match --memprofile --mime -o --output -p --preserve --preserve-links -r --recursive --type --url -v --verbose --version -w --watch --css-precision --html-keep-comments --html-keep-conditional-comments --html-keep-default-attrvals --html-keep-document-tags --html-keep-end-tags --html-keep-quotes --html-keep-whitespace --js-precision --js-keep-var-names --js-no-nullish-operator --json-precision --json-keep-numbers --svg-keep-comments --svg-precision -s --sync --xml-keep-whitespace"
flags="-a --all --bundle --cpuprofile -l --list --match --memprofile --mime -o --output -p --preserve --preserve-links -r --recursive --type --url -v --verbose --version -w --watch --css-precision --html-keep-comments --html-keep-conditional-comments --html-keep-default-attrvals --html-keep-document-tags --html-keep-end-tags --html-keep-quotes --html-keep-whitespace --js-precision --js-keep-var-names --js-version --json-precision --json-keep-numbers --svg-keep-comments --svg-precision -s --sync --xml-keep-whitespace"
mimes="text/css text/html text/javascript application/javascript application/json image/svg+xml text/xml application/xml"
types="css html js json svg xml"

Expand Down
2 changes: 1 addition & 1 deletion cmd/minify/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ func run() int {
flag.BoolVar(&htmlMinifier.KeepQuotes, "html-keep-quotes", false, "Preserve quotes around attribute values")
flag.IntVar(&jsMinifier.Precision, "js-precision", 0, "Number of significant digits to preserve in numbers, 0 is all")
flag.BoolVar(&jsMinifier.KeepVarNames, "js-keep-var-names", false, "Preserve original variable names")
flag.BoolVar(&jsMinifier.NoNullishOperator, "js-no-nullish-operator", false, "Don't use the ?? nullish coalescing operator")
flag.IntVar(&jsMinifier.Version, "js-version", 0, "ECMAScript version to toggle supported optimizations (e.g. 2019, 2020), by default 0 is the latest version")
flag.IntVar(&jsonMinifier.Precision, "json-precision", 0, "Number of significant digits to preserve in numbers, 0 is all")
flag.BoolVar(&jsonMinifier.KeepNumbers, "json-keep-numbers", false, "Preserve original numbers instead of minifying them")
flag.BoolVar(&svgMinifier.KeepComments, "svg-keep-comments", false, "Preserve all comments")
Expand Down
14 changes: 12 additions & 2 deletions js/js.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"github.com/tdewolff/parse/v2/js"
)

const esNext = 2022

type blockType int

const (
Expand All @@ -23,7 +25,8 @@ type Minifier struct {
Precision int // number of significant digits
KeepVarNames bool
useAlphabetVarNames bool
NoNullishOperator bool
NoNullishOperator bool // DEPRECATED, use version ES2020
Version int
}

// Minify minifies JS data, it reads from r and writes to w.
Expand All @@ -33,6 +36,13 @@ func Minify(m *minify.M, w io.Writer, r io.Reader, params map[string]string) err

// Minify minifies JS data, it reads from r and writes to w.
func (o *Minifier) Minify(_ *minify.M, w io.Writer, r io.Reader, _ map[string]string) error {
if o.Version == 0 {
o.Version = esNext
}
if 2019 < o.Version && o.NoNullishOperator {
o.Version = 2019 // nullish operator was introduced in ES2020
}

z := parse.NewInput(r)
ast, err := js.Parse(z, js.Options{WhileToFor: true})
if err != nil {
Expand Down Expand Up @@ -303,7 +313,7 @@ func (m *jsMinifier) minifyStmt(i js.IStmt) {
if stmt.Catch != nil {
m.write(catchBytes)
stmt.Catch.List = optimizeStmtList(stmt.Catch.List, defaultBlock)
if v, ok := stmt.Binding.(*js.Var); ok && v.Uses == 1 {
if v, ok := stmt.Binding.(*js.Var); ok && v.Uses == 1 && 2019 <= m.o.Version {
stmt.Catch.Scope.Declared = stmt.Catch.Scope.Declared[1:]
stmt.Binding = nil
}
Expand Down
31 changes: 31 additions & 0 deletions js/js_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -881,6 +881,37 @@ func TestJSVarRenaming(t *testing.T) {
}
}

func TestJSVersion(t *testing.T) {
versions := []int{esNext, 2020, 2019, 2018}

jsTests := []struct {
version int
js string
before string
after string
}{
{2020, `a==null?b:a`, `a==null?b:a`, `a??b`},
{2019, `try{}catch(a){}`, `try{}catch(a){}`, `try{}catch{}`},
}

m := minify.New()
for _, tt := range jsTests {
for _, version := range versions {
t.Run(fmt.Sprintf("%d/%v", version, tt.js), func(t *testing.T) {
r := bytes.NewBufferString(tt.js)
w := &bytes.Buffer{}
o := Minifier{KeepVarNames: true, useAlphabetVarNames: true, Version: version}
err := o.Minify(m, w, r, nil)
if version < tt.version {
test.Minify(t, tt.js, err, w.String(), tt.before)
} else {
test.Minify(t, tt.js, err, w.String(), tt.after)
}
})
}
}
}

func TestReaderError(t *testing.T) {
r := test.NewErrorReader(0)
w := &bytes.Buffer{}
Expand Down
2 changes: 1 addition & 1 deletion js/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -825,7 +825,7 @@ func (m *jsMinifier) optimizeCondExpr(expr *js.CondExpr, prec js.OpPrec) js.IExp
} else if isEqualExpr(expr.X, expr.Y) {
// if true and false bodies are equal
return groupExpr(&js.CommaExpr{[]js.IExpr{expr.Cond, expr.X}}, prec)
} else if nullishExpr, ok := toNullishExpr(expr); ok && !m.o.NoNullishOperator {
} else if nullishExpr, ok := toNullishExpr(expr); ok && 2020 <= m.o.Version {
// no need to check whether left/right need to add groups, as the space saving is always more
return nullishExpr
} else {
Expand Down

0 comments on commit a52d606

Please sign in to comment.