Skip to content

Commit

Permalink
JS: minify template literals, fixes #529
Browse files Browse the repository at this point in the history
  • Loading branch information
tdewolff committed Sep 8, 2022
1 parent 655ab04 commit 6923a73
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 3 deletions.
4 changes: 2 additions & 2 deletions js/js.go
Original file line number Diff line number Diff line change
Expand Up @@ -1139,10 +1139,10 @@ func (m *jsMinifier) minifyExpr(i js.IExpr, prec js.OpPrec) {
parentInFor := m.inFor
m.inFor = false
for _, item := range expr.List {
m.write(item.Value)
m.write(replaceEscapes(item.Value, '`', 1, 2))
m.minifyExpr(item.Expr, js.OpExpr)
}
m.write(expr.Tail)
m.write(replaceEscapes(expr.Tail, '`', 1, 1))
m.inFor = parentInFor
case *js.NewExpr:
if expr.Args == nil && js.OpLHS < prec && prec != js.OpNew {
Expand Down
1 change: 1 addition & 0 deletions js/js_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ func TestJS(t *testing.T) {
{`0,"\"\"a'"`, "0,`\"\"a'`"},
{`0,"'" + '"'`, "0,`'\"`"},
{`0,'"' + "'"`, "0,`\"'`"},
{"0,`\\n\\'\\$`", "0,`\n'\\$`"},
{`0,"a"+"b"+5`, `0,"ab"+5`},
{`0,5+"a"+"b"`, `0,5+"ab"`},
{`0,"a"+"b"+5+"c"+"d"`, `0,"ab"+5+"cd"`},
Expand Down
7 changes: 6 additions & 1 deletion js/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -970,10 +970,15 @@ func minifyString(b []byte, allowTemplate bool) []byte {
b[0] = quote
b[len(b)-1] = quote

// strip unnecessary escapes
return replaceEscapes(b, quote, 1, 1)
}

func replaceEscapes(b []byte, quote byte, prefix, suffix int) []byte {
// strip unnecessary escapes
j := 0
start := 0
for i := 1; i < len(b)-1; i++ {
for i := prefix; i < len(b)-suffix; i++ {
if c := b[i]; c == '\\' {
c = b[i+1]
if c == quote || c == '\\' || c == 'u' || c == '0' && (i+2 == len(b)-1 || b[i+2] < '0' || '7' < b[i+2]) || quote != '`' && (c == 'n' || c == 'r') {
Expand Down

0 comments on commit 6923a73

Please sign in to comment.