assetmin

package module
v0.0.72 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 1, 2026 License: MIT Imports: 19 Imported by: 0

README

📦 AssetMin

Project Badges

🚀 A lightweight and efficient web asset packager and minifier for Go applications

AssetMin bundles and minifies your JavaScript, CSS, SVG, and HTML files with support for both memory-based and disk-based serving. Perfect for development and production workflows.

🛠️ Primary Use Case

AssetMin is primarily used in the APP framework for developing full stack projects with Go. It provides an efficient solution for managing and optimizing web assets, ensuring seamless integration into your Go workflow.

✨ Features

  • 🔄 Live Asset Processing - Event-driven file processing with automatic cache invalidation
  • 🗜️ Minification - Optimized minification using tdewolff/minify
  • 💾 Dual Work Modes - Memory-only (dev) or disk-based (production) serving
  • 🌐 HTTP Serving - Built-in HTTP handlers with configurable URL prefixes
  • 🔒 Thread-Safe - Concurrent file processing with mutex protection
  • 📦 Asset Bundling - Combines multiple files into optimized bundles
  • Smart Caching - In-memory cache for instant HTTP responses

📥 Installation

go get github.com/tinywasm/assetmin

🚀 Quick Start

package main

import (
	"log"
	"net/http"
	
	"github.com/tinywasm/assetmin"
)

func main() {
	// Create configuration
	config := &assetmin.Config{
		OutputDir: "web/public",
		Logger: func(msg ...any) {
			log.Println(msg...)
		},
		AppName: "MyApp",
		AssetsURLPrefix: "/assets/",
	}
	
	// Initialize AssetMin
	am := assetmin.NewAssetMin(config)
	
	// Register HTTP routes
	mux := http.NewServeMux()
	am.RegisterRoutes(mux)
	
	// Process files
	am.NewFileEvent("button.css", ".css", "./src/button.css", "create")
	am.NewFileEvent("app.js", ".js", "./src/app.js", "create")
	
	// Start server
	log.Println("Server running on :8080")
	http.ListenAndServe(":8080", mux)
}

🔄 How It Works

  1. Configure - Set output directory and options
  2. Initialize - Create AssetMin instance
  3. Process Events - Notify AssetMin of file changes
  4. Serve - Assets are minified, cached, and served via HTTP
  5. Deploy - Switch to DiskMode to write optimized files

📚 Documentation

🎯 Core API

Configuration
type Config struct {
    OutputDir               string                 // Output directory for assets
    Logger                  func(message ...any)   // Logging function
    GetRuntimeInitializerJS func() (string, error) // JS initialization code
    AppName                 string                 // Application name
    AssetsURLPrefix         string                 // URL prefix for assets
}
Main Methods
// Create new instance
am := assetmin.NewAssetMin(config)

// Process file events
am.NewFileEvent(fileName, extension, filePath, event)

// Register HTTP routes
am.RegisterRoutes(mux)

// Work mode control
am.SetWorkMode(assetmin.DiskMode)    // Write to disk
am.SetWorkMode(assetmin.MemoryMode)  // Memory only (default)

// Manual asset refresh
am.RefreshAsset(".js")  // Rebuild JavaScript bundle

🌐 HTTP Routes

AssetMin automatically registers routes for all assets:

Asset Default Route With Prefix /assets/
index.html / /
style.css /style.css /assets/style.css
script.js /script.js /assets/script.js
sprite.svg /sprite.svg /assets/sprite.svg
favicon.svg /favicon.svg /assets/favicon.svg

💾 Work Modes

MemoryMode (Default)
  • Serves assets from in-memory cache
  • No disk writes
  • Fastest for development
DiskMode
  • Writes assets to disk on changes
  • Still serves from cache for performance
  • Useful for production builds
// Development
am.SetWorkMode(assetmin.MemoryMode)

// Production
am.SetWorkMode(assetmin.DiskMode)
am.EnsureOutputDirectoryExists()

📋 Supported File Types

  • JavaScript (.js) - Bundled with automatic 'use strict' handling
  • CSS (.css) - Merged and minified stylesheets
  • SVG (.svg) - Icon sprites and favicons
  • HTML (.html) - Template fragments (complete documents ignored)

🔧 Advanced Usage

See the API Documentation for:

  • WASM integration examples
  • File watcher integration
  • Development vs production setup
  • Thread safety details
  • Performance considerations

📋 Roadmap

  • ✅ Config Simplification
  • ✅ Asset Caching System
  • ✅ HTTP Routes & Work Modes
  • 🔄 Template System Refactor
  • 🔄 TUI Integration
  • 🔄 Enhanced SSR Support

See docs/ROADMAP.md for details.


📄 License

This project is licensed under the [MIT] License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FileWrite

func FileWrite(pathFile string, data bytes.Buffer) error

pathFile e.g., "theme/htmlMainFileName" data e.g., *bytes.Buffer NOTE: The buffer data will be cleared after writing the file

func NewFaviconSvgHandler

func NewFaviconSvgHandler(ac *Config, outputName string) *asset

NewFaviconSvgHandler creates a handler for favicon.svg that simply minifies and copies the file without sprite wrapping. This handler processes standalone SVG files like favicon.svg

func NewHtmlHandler

func NewHtmlHandler(ac *Config, outputName, cssURL, jsURL string) *asset

NewHtmlHandler creates an HTML asset handler using the provided output filename

func NewSvgHandler

func NewSvgHandler(ac *Config, outputName string) *asset

Types

type AssetMin

type AssetMin struct {
	*Config
	// contains filtered or unexported fields
}

func NewAssetMin

func NewAssetMin(ac *Config) *AssetMin

func (*AssetMin) BuildOnDisk added in v0.0.71

func (c *AssetMin) BuildOnDisk() bool

BuildOnDisk returns true if assets are written to disk.

func (*AssetMin) EnsureOutputDirectoryExists

func (c *AssetMin) EnsureOutputDirectoryExists()

func (*AssetMin) Logger added in v0.0.71

func (c *AssetMin) Logger(messages ...any)

func (*AssetMin) MainInputFileRelativePath added in v0.0.70

func (c *AssetMin) MainInputFileRelativePath() string

MainInputFileRelativePath returns the main input file path. AssetMin manages multiple assets, so returns empty. Used by DevWatch for specific file watching logic.

func (*AssetMin) MainOutputFileAbsolutePath added in v0.0.70

func (c *AssetMin) MainOutputFileAbsolutePath() string

MainOutputFileAbsolutePath returns the main output file path. AssetMin manages multiple outputs, so returns empty. Used by DevWatch for exclusion logic (handled by UnobservedFiles instead)

func (*AssetMin) Name added in v0.0.71

func (c *AssetMin) Name() string

func (*AssetMin) NewFileEvent

func (c *AssetMin) NewFileEvent(fileName, extension, filePath, event string) error

event: create, remove, write, rename

func (*AssetMin) RefreshAsset

func (c *AssetMin) RefreshAsset(extension string)

func (*AssetMin) RegisterRoutes

func (c *AssetMin) RegisterRoutes(mux *http.ServeMux)

RegisterRoutes registers the HTTP handlers for all assets.

func (*AssetMin) SetBuildOnDisk added in v0.0.71

func (c *AssetMin) SetBuildOnDisk(onDisk bool)

SetBuildOnDisk sets the work mode for AssetMin.

func (*AssetMin) SetLog added in v0.0.71

func (c *AssetMin) SetLog(f func(message ...any))

func (*AssetMin) ShouldCompileToWasm added in v0.0.70

func (c *AssetMin) ShouldCompileToWasm(fileName, filePath string) bool

ShouldCompileToWasm checks if the file triggers WASM compilation. AssetMin handles assets, not WASM, so always returns false.

func (*AssetMin) SupportedExtensions

func (c *AssetMin) SupportedExtensions() []string

func (*AssetMin) UnobservedFiles

func (c *AssetMin) UnobservedFiles() []string

func (*AssetMin) UpdateFileContentInMemory

func (c *AssetMin) UpdateFileContentInMemory(filePath, extension, event string, content []byte) (*asset, error)

type Config

type Config struct {
	OutputDir               string                 // eg: web/static, web/public, web/assets
	GetRuntimeInitializerJS func() (string, error) // javascript code to initialize the wasm or other handlers
	AppName                 string                 // Application name for templates (default: "MyApp")
	AssetsURLPrefix         string                 // New: for HTTP routes
}

type TestEnvironment

type TestEnvironment struct {
	BaseDir       string
	ThemeDir      string
	PublicDir     string
	ModulesDir    string
	MainJsPath    string
	MainCssPath   string
	MainSvgPath   string
	MainHtmlPath  string
	AssetsHandler *AssetMin
	// contains filtered or unexported fields
}

TestEnvironment holds all the paths and components needed for asset tests

func (*TestEnvironment) CleanDirectory

func (env *TestEnvironment) CleanDirectory()

CleanDirectory removes all content from the test directory but keeps the directory itself

func (*TestEnvironment) CreateModulesDir

func (env *TestEnvironment) CreateModulesDir() *TestEnvironment

CreateModulesDir creates the modules directory if it doesn't exist

func (*TestEnvironment) CreatePublicDir

func (env *TestEnvironment) CreatePublicDir() *TestEnvironment

CreatePublicDir creates the public directory if it doesn't exist

func (*TestEnvironment) CreateThemeDir

func (env *TestEnvironment) CreateThemeDir() *TestEnvironment

CreateThemeDir creates the theme directory if it doesn't exist

func (*TestEnvironment) TestConcurrentFileProcessing

func (env *TestEnvironment) TestConcurrentFileProcessing(fileExtension string, fileCount int)

TestConcurrentFileProcessing is a reusable function to test concurrent file processing for both JS and CSS.

func (*TestEnvironment) TestFileCRUDOperations

func (env *TestEnvironment) TestFileCRUDOperations(fileExtension string)

TestFileCRUDOperations tests the complete CRUD cycle (create, write, remove) for a file

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL