tdewolff / minify

Go minifiers for web formats

Home Page:https://go.tacodewolff.nl/minify

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Json string is wrapped with backtick

gyuber opened this issue · comments

if exist double, single quote in string, string is wrapped with backtick
but backtick is compatible depending on the browser. ( ie browser )
example)
https://play.golang.org/p/I5c1a6yOtjk

type Json struct {
    HTML string `json:"html"`
}
func main() {
    json := Json{}
    json.HTML = `<div class="test" onclick="test('test'))">`
    html := `<script> var json = {{ . }}</script>>`

    t := template.Must(template.New("html").Parse(html))
    var tpl bytes.Buffer
    t.Execute(&tpl, json)

    s, err := m.String("text/html", tpl.String())
    if err != nil {
        panic(err)
    }
    fmt.Println(s)
}

<script>var json={html:`<div class="test" onclick="test('test'))">`}</script>>

Can You Keep value in html/template (tpl.String() ?

Using backticks (template literals) is the smallest version of the code. The only browser that doesn't support this is IE, but since it is not supported anymore (https://support.microsoft.com/en-us/windows/internet-explorer-help-23360e49-9cd3-4dda-ba52-705336cc0de2) I wasn't planning on supporting it. However, perhaps we could support ECMAVersion < 2015 (template literals were added in 2015) in the JS minifier.

Implemented, please specify Version < 2015 in the JS minifier options! Please let me know if that fixes your issue.

@tdewolff
Add option !

m.Add("text/html", &js.Minifier{
    Version: 2014,
})

but panic..

panic: unexpected < in expression on line 1 and column 1
    1: <script> var json = {"html":"\u003cdiv class=\"test\" onc...

how to use JS minifier options?

Share my code
https://go.dev/play/p/aIz-lw9ps-I

Please see the documentation, you're trying to minify text/html with a JavaScript minifier! Use:

m.AddFuncRegexp(regexp.MustCompile("^(application|text)/(x-)?(java|ecma|j|live)script(1\\.[0-5])?$|^module$"), &js.Minifier{
    Version: 2014,
})

// ...

s, err := m.String("text/html", tpl.String())

@tdewolff
my html code mixed html & javscript
See below code

<body>
   <div>...</div>
</body>
<script>
  var json = {{ . }}
</script>

So I minified it to text/html
if html & script are mixed, must be run it separately?

No, you minify a file only once. It is initially parsed as HTML, but since HTML can contains XML, JavaScript or CSS, each part is parsed successively by the corresponding minifiers. I've added support for HTML templates in script/style by the way.

oh! perpect!
my code works well!
https://go.dev/play/p/OKtgsUk4Qoy