Try it yourself with our free Js Minifier tool — runs entirely in your browser, no signup needed.

How to Minify JavaScript in Go

How to minify JavaScript in Go

Minifying JavaScript is an essential step in optimizing web applications for production. By removing unnecessary characters, such as whitespace and comments, minification reduces the size of JavaScript files, leading to faster page loads and improved user experience. In this article, we will explore how to minify JavaScript in Go using the github.com/tdewolff/minify package.

Quick Example

Here is a minimal example that minifies a JavaScript file:

package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/tdewolff/minify"
	"github.com/tdewolff/minify/js"
)

func main() {
	minifier := minify.New()
	minifier.AddFunc("application/javascript", js.Minify)

	input := []byte("function add(a, b) { return a + b; }")
	output := bytes.NewBuffer(nil)

	err := minifier.Minify("application/javascript", output, bytes.NewReader(input))
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(output.String())
}

To use this code, install the github.com/tdewolff/minify package using the following command:

go get -u github.com/tdewolff/minify

Step-by-Step Breakdown

Let's walk through the code line by line:

  1. We import the necessary packages, including github.com/tdewolff/minify and github.com/tdewolff/minify/js.
  2. We create a new minify instance using minify.New().
  3. We add a minification function for JavaScript files using minifier.AddFunc. In this case, we use the js.Minify function provided by the github.com/tdewolff/minify/js package.
  4. We define the input JavaScript code as a byte slice.
  5. We create a new buffer to store the minified output.
  6. We call the Minify method on the minifier instance, passing in the MIME type, output buffer, and input reader.
  7. We check for any errors and log them if necessary.

Handling Edge Cases

Here are some common edge cases to consider:

Empty/null input

input := []byte{}
output := bytes.NewBuffer(nil)
err := minifier.Minify("application/javascript", output, bytes.NewReader(input))
if err != nil {
	log.Fatal(err)
}
fmt.Println(output.String()) // Output: ""

In this case, the minifier will simply return an empty string.

Invalid input

input := []byte(" invalid JavaScript code ")
output := bytes.NewBuffer(nil)
err := minifier.Minify("application/javascript", output, bytes.NewReader(input))
if err != nil {
	log.Fatal(err)
}
fmt.Println(output.String()) // Output: " invalid JavaScript code "

In this case, the minifier will return the original input, as it is not valid JavaScript code.

Large input

largeInput := make([]byte, 1024*1024) // 1MB
output := bytes.NewBuffer(nil)
err := minifier.Minify("application/javascript", output, bytes.NewReader(largeInput))
if err != nil {
	log.Fatal(err)
}
fmt.Println(output.String()) // Output: minified JavaScript code

In this case, the minifier will still work correctly, but may take longer to process the large input.

Unicode/special characters

input := []byte("function add(a, b) { return a + b; } // ")
output := bytes.NewBuffer(nil)
err := minifier.Minify("application/javascript", output, bytes.NewReader(input))
if err != nil {
	log.Fatal(err)
}
fmt.Println(output.String()) // Output: "function add(a,b){return a+b;}"

In this case, the minifier will correctly handle Unicode characters and special characters.

Common Mistakes

Here are some common mistakes developers make when minifying JavaScript in Go:

Mistake 1: Not checking for errors

minifier.Minify("application/javascript", output, bytes.NewReader(input))
fmt.Println(output.String()) // This will panic if Minify returns an error

Corrected code:

err := minifier.Minify("application/javascript", output, bytes.NewReader(input))
if err != nil {
	log.Fatal(err)
}
fmt.Println(output.String())

Mistake 2: Using the wrong MIME type

minifier.Minify("text/javascript", output, bytes.NewReader(input))

Corrected code:

minifier.Minify("application/javascript", output, bytes.NewReader(input))

Mistake 3: Not using a buffer for output

err := minifier.Minify("application/javascript", nil, bytes.NewReader(input))
if err != nil {
	log.Fatal(err)
}

Corrected code:

output := bytes.NewBuffer(nil)
err := minifier.Minify("application/javascript", output, bytes.NewReader(input))
if err != nil {
	log.Fatal(err)
}
fmt.Println(output.String())

Performance Tips

Here are some practical performance tips for minifying JavaScript in Go:

  1. Use a buffer for output instead of writing directly to a file or network connection.
  2. Use the minify.Minify method instead of minify.MinifyBytes for large inputs.
  3. Avoid minifying JavaScript code that is already minified.

FAQ

Q: What is the difference between minify.Minify and minify.MinifyBytes?

A: minify.Minify is more efficient for large inputs, while minify.MinifyBytes is more convenient for small inputs.

Q: Can I use this package to minify other types of files?

A: No, this package is specifically designed for minifying JavaScript files.

Q: How do I handle errors when minifying JavaScript code?

A: Check the error return value of the Minify method and log any errors using the log package.

Q: Can I use this package in a concurrent environment?

A: Yes, this package is safe for use in concurrent environments.

Q: How do I install the github.com/tdewolff/minify package?

A: Use the go get command: go get -u github.com/tdewolff/minify

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp