Skip to content

Commit

Permalink
JS: don't remove braces when there are lexical declarations, fixes #326
Browse files Browse the repository at this point in the history
  • Loading branch information
tdewolff committed Sep 4, 2020
1 parent 5eb5f20 commit 96fbb7d
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ module github.com/tdewolff/minify/v2

go 1.13

replace github.com/tdewolff/parse/v2 => ../parse

require (
github.com/cheekybits/is v0.0.0-20150225183255-68e9c0620927 // indirect
github.com/dustin/go-humanize v1.0.0
Expand Down
10 changes: 9 additions & 1 deletion js/js.go
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,14 @@ func (m *jsMinifier) minifyBlockAsStmt(blockStmt *js.BlockStmt, blockType blockT
// minify block when statement is expected, i.e. semicolon if empty or remove braces for single statement
// assume we already renamed the scope
blockStmt.List = m.optimizeStmtList(blockStmt.List, blockType)
if 1 < len(blockStmt.List) {
hasLexicalVars := false
for _, v := range blockStmt.Scope.Declared[blockStmt.Scope.NumForInit:] {
if v.Decl == js.LexicalDecl {
hasLexicalVars = true
break
}
}
if 1 < len(blockStmt.List) || hasLexicalVars {
m.minifyBlockStmt(*blockStmt)
} else if len(blockStmt.List) == 1 {
m.minifyStmt(blockStmt.List[0])
Expand All @@ -407,6 +414,7 @@ func (m *jsMinifier) minifyStmtOrBlock(i js.IStmt, blockType blockType) {
m.renamer.renameScope(blockStmt.Scope)
m.minifyBlockAsStmt(blockStmt, blockType)
} else {
// optimizeStmtList can in some cases expand one stmt to two shorter stmts
list := m.optimizeStmtList([]js.IStmt{i}, blockType)
if len(list) == 1 {
m.minifyStmt(list[0])
Expand Down
5 changes: 3 additions & 2 deletions js/js_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ func TestJS(t *testing.T) {
{`for (a in b){a}`, `for(a in b)a`},
{`for (var a of b){a}`, `for(var a of b)a`},
{`for (a of b){a}`, `for(a of b)a`},
{`for (;;){let a}`, `for(;;){let a}`},
{`while(a < 10){a}`, `while(a<10)a`},
{`while(a < 10){a;b}`, `while(a<10)a,b`},
{`while(a < 10){while(b);c}`, `while(a<10){while(b);c}`},
Expand Down Expand Up @@ -276,8 +277,8 @@ func TestJS(t *testing.T) {
{`var a=5;var b=6;a=7`, `var a=5,b=6;a=7`},
{`var a;var b=6;z=7`, `var b=6,a;z=7`},
{`for(var a=6,b=7;;);var c=8`, `for(var a=6,b=7,c=8;;);`},
{`for(var c;b;){let a=8};var a`, `for(var c,a;b;)let a=8`},
{`for(;b;){let a=8};var a;var b`, `for(var a,b;b;)let a=8`},
{`for(var c;b;){let a=8};var a`, `for(var c,a;b;){let a=8}`},
{`for(;b;){let a=8};var a;var b`, `for(var a,b;b;){let a=8}`},

// function and method declarations
{`function g(){return}`, `function g(){}`},
Expand Down

0 comments on commit 96fbb7d

Please sign in to comment.