tdewolff/minify

repository·master·Indexed 26 days ago

https://github.com/tdewolff/minify

A high-performance minification package written in Go providing minifiers for HTML5, CSS3, JS, JSON, SVG, and XML. It includes a CLI tool, an extensible interface for custom minifiers, and official bindings for JavaScript (@tdewolff/minify) and Python.

Tokens
11.4K
Snippets
32
Records
64
Agent score
83%

What's inside tdewolff/minify

  1. Integrate Minify as HTTP Middleware

    master

    Minify can be used as middleware in a Go web server. Use m.MiddlewareWithError(handler) to wrap an existing http.Handler. This will automatically minify responses.

    Important: When using MiddlewareWithError, you must close the response writer (which is returned as an io.Closer) to ensure errors are captured and the response is properly finalized.

    // Standard Middleware usage
    fs := http.FileServer(http.Dir("www/"))
    http.Handle("/", m.MiddlewareWithError(fs))
    
    // Handling errors in custom handlers with Middleware
    m.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "text/html")
        _, _ = w.Write([]byte(input))
    
        // You must cast the writer to io.Closer and close it
        if err = w.(io.Closer).Close(); err != nil {
            panic(err)
        }
    })).ServeHTTP(rec, req)
  2. Use the Minify CLI

    master

    The minify command minifies input files or directories based on their extension or an explicitly provided type.

    Basic Usage

    • Minify a single file to a new file: minify -o <output> <input>
    • Minify to stdout: minify <input>
    • Minify via stdin: When using standard input, you must specify the type using --type.
      minify --type=js < script.js > script-min.js

    Directory Processing

    • Recursive minification: Use -r to process directories and subdirectories.
    • Trailing slashes:
      • A trailing slash in the source path (src/) copies all files inside the directory.
      • A trailing slash in the destination path (out/) forces writing into a directory.

    Advanced Features

    • Bundling: Use -b or --bundle to concatenate multiple input files into a single output file.
    • Watching: Use -w or --watch to automatically re-minify files when they change.
    • In-place: Use -i or --inplace to overwrite the input files.
    minify -o index-min.html index.html
  3. Use Minify as HTTP Middleware

    master

    You can minify resources on-the-fly by wrapping an http.Handler with m.Middleware(handler).

    • The middleware wraps the response writer and removes the Content-Length header.
    • The minifier is selected based on the Content-Type header or, if empty, the file extension in the request URI.
    • Performance Tip: Since this is on-the-fly processing, you should cache the results to avoid repeated minification overhead.
    fs := http.FileServer(http.Dir("www/"))
    http.Handle("/", m.Middleware(fs))
  4. Initialize a Minifier in Go

    master

    Use minify.New() to retrieve a *minify.M struct. This struct holds a mapping of mediatypes to their respective minification functions. You must register minifiers (e.g., CSS, HTML, JS) using AddFunc, AddFuncRegexp, Add, or AddRegexp before they can be used.

    Note: Input streams are buffered for performance, but output streams are not. It is recommended to preallocate an output buffer equal to the input size or use bufio to wrap the output writer.

    ```go
    m := minify.New()
    m.AddFunc("text/css", css.Minify)
    m.AddFunc("text/html", html.Minify)
    ```埋
  5. Install the Minify CLI

    master

    You can install the minify CLI tool via several methods depending on your operating system or environment.

    From Source (Go/Git)

    Ensure you have Go and Git installed, then run:

    mkdir $HOME/src
    cd $HOME/src
    git clone https://github.com/tdewolff/minify.git
    cd minify
    make install

    If make is not available, use:

    go install ./cmd/minify
    source minify_bash_tab_completion

    To install the latest version directly via Go:

    go install github.com/tdewolff/minify/v2/cmd/minify@latest

    Package Managers

    • Arch Linux: yay -S minify
    • FreeBSD: pkg install minify
    • Alpine Linux: apk add minify (requires community repo)
    • MacOS: brew install tdewolff/tap/minify
    • Debian / Ubuntu: sudo apt install minify (may be outdated)

    Docker

    Pull the image:

    docker pull tdewolff/minify

    Run in interactive mode:

    docker run -i tdewolff/minify sh -c 'echo "(function(){ if (a == false) { return 0; } else { return 1; } })();" | minify --type js'
    go install github.com/tdewolff/minify/v2/cmd/minify@latest
  6. Install Minify via language bindings

    master

    Minify is available for several other environments:

    • JavaScript (Node.js 20.19+): npm i @tdewolff/minify
    • Python: pip install tdewolff-minify
    • Windows (via Scoop): scoop install main/minify
    • .NET: Install-Package NMinify or dotnet add package NMinify
  7. Use the Python Minify API

    master

    The Python bindings provide three primary functions: minify.config() to set minifier options, minify.string() to minify a string in memory, and minify.file() to minify a file on disk. All functions require a mediatype as the first argument.

    import minify
    
    # Configure minifier options
    minify.config({
        'css-precision': 0,
        'html-keep-comments': False,
        'js-version': 0,
    })
    
    # Minify a string
    s = minify.string('text/html', '<span style="color:#ff0000;" class="text">Some  text</span>')
    print(s)
    
    # Minify a file (creates output_file from input_file)
    minify.file('text/html', 'example.html', 'example.min.html')
  8. Install Minify for Go

    master

    To use Minify in your Go project, ensure you have Git and Go (1.18 or higher) installed. Initialize your module and fetch the package using the following commands:

    mkdir Project
    cd Project
    go mod init
    go get -u github.com/tdewolff/minify/v2

    To clean up your go.mod and go.sum files, you can optionally run go mod tidy.

  9. Import Minify subpackages in Go

    master

    To use the various minifiers (HTML, CSS, JS, etc.), you must import the core package along with the specific minifier implementations:

    import (
    	"github.com/tdewolff/minify/v2"
    	"github.com/tdewolff/minify/v2/css"
    	"github.com/tdewolff/minify/v2/html"
    	"github.com/tdewolff/minify/v2/js"
    	"github.com/tdewolff/minify/v2/json"
    	"github.com/tdewolff/minify/v2/svg"
    	"github.com/tdewolff/minify/v2/xml"
    )