assetmin

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: May 14, 2026 License: MIT Imports: 29 Imported by: 2

README

AssetMin

AssetMin is a thread-safe, concurrent asset pipeline and bundler for Go web applications. It manages CSS, JavaScript, SVG sprites, and HTML templates, providing minification and caching.

Features

  • Bundling & Minification: CSS, JS, HTML, and SVG.
  • SSR Support: Automatic discovery and extraction of assets from Go modules.
  • Component Registration: Extract assets from live Go structs.
  • Typed CSS: Native support for github.com/tinywasm/css stylesheets.
  • Memory & Disk Modes: Serve directly from RAM or build to disk.
  • Hot Reload: Instant thread-safe cache regeneration.

Documentation

  1. Architecture
  2. Assets
  3. Component Registration
  4. SSR & Module Extraction
  5. API Reference
  6. HTTP Handlers
Diagrams

Performance

The compile-and-invoke SSR extraction mechanism provides:

  • Fast cold extraction: ~450ms for typical projects.
  • Hash-based caching: Instant warm extractions (~1ms).
  • Full typed CSS support without performance penalty.

See Benchmark Suite for detailed performance measurements.

Installation

go get github.com/tinywasm/assetmin

Get Started

package main

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

func main() {
	config := &assetmin.Config{
		OutputDir:       "./public",
		RootDir:         ".",
		AppName:         "MyApp",
		AssetsURLPrefix: "/static/",
	}

	am := assetmin.NewAssetMin(config)

	// Load assets from imported Go modules asynchronously
	am.LoadSSRModules()
	
	log.Println("Asset bundler is ready!")
}

For more advanced use cases, such as registration of components or setting up file watchers, please refer to the documentation.

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 FileWriteSafe added in v0.0.76

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

FileWriteSafe writes the data to pathFile only if the file does not already exist.

func GenerateExtractorMain added in v0.3.0

func GenerateExtractorMain(outputFile string, modules []Module) error

GenerateExtractorMain writes a main.go file that imports all modules and collects their assets.

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, faviconURL string) *asset

NewHtmlHandler creates an HTML asset handler using the provided output filename

func NewSvgHandler

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

func ParseExistingHtmlContent added in v0.2.2

func ParseExistingHtmlContent(content string) (openContent, closeContent string)

ParseExistingHtmlContent is a public wrapper for tests.

func RewriteAssetUrls added in v0.2.2

func RewriteAssetUrls(html string, newRoot string) string

RewriteAssetUrls is a public wrapper for tests.

func StripLeadingUseStrict added in v0.2.2

func StripLeadingUseStrict(b []byte) []byte

StripLeadingUseStrict is a public wrapper for tests.

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) ContainsCSS added in v0.2.2

func (c *AssetMin) ContainsCSS(substr string) bool

ContainsCSS checks if the CSS bundle contains the given substring.

func (*AssetMin) ContainsHTML added in v0.2.2

func (c *AssetMin) ContainsHTML(substr string) bool

ContainsHTML checks if the HTML bundle contains the given substring.

func (*AssetMin) ContainsJS added in v0.2.2

func (c *AssetMin) ContainsJS(substr string) bool

ContainsJS checks if the JS bundle contains the given substring.

func (*AssetMin) ContainsSVG added in v0.2.2

func (c *AssetMin) ContainsSVG(substr string) bool

ContainsSVG checks if the SVG sprite contains the given substring.

func (*AssetMin) EnsureOutputDirectoryExists

func (c *AssetMin) EnsureOutputDirectoryExists()

func (*AssetMin) Execute added in v0.2.3

func (c *AssetMin) Execute()

Execute toggles minification and regenerates all assets.

func (*AssetMin) GetCSSURLPath added in v0.2.2

func (c *AssetMin) GetCSSURLPath() string

GetCSSURLPath returns the URL path for the main CSS file.

func (*AssetMin) GetCachedHTML added in v0.2.2

func (c *AssetMin) GetCachedHTML() []byte

GetCachedHTML returns the cached minified HTML content.

func (*AssetMin) GetFaviconURLPath added in v0.2.2

func (c *AssetMin) GetFaviconURLPath() string

GetFaviconURLPath returns the URL path for the favicon file.

func (*AssetMin) GetInitCodeJS added in v0.2.2

func (c *AssetMin) GetInitCodeJS() (string, error)

GetInitCodeJS returns the init code for the JS bundle.

func (*AssetMin) GetJSURLPath added in v0.2.2

func (c *AssetMin) GetJSURLPath() string

GetJSURLPath returns the URL path for the main JS file.

func (*AssetMin) GetMainCssPath added in v0.2.2

func (c *AssetMin) GetMainCssPath() string

GetMainCssPath returns the output path of the main CSS file.

func (*AssetMin) GetMainHtmlPath added in v0.2.2

func (c *AssetMin) GetMainHtmlPath() string

GetMainHtmlPath returns the output path of the main HTML file.

func (*AssetMin) GetMainJsPath added in v0.2.2

func (c *AssetMin) GetMainJsPath() string

GetMainJsPath returns the output path of the main JS file.

func (*AssetMin) GetMainSvgPath added in v0.2.2

func (c *AssetMin) GetMainSvgPath() string

GetMainSvgPath returns the output path of the main SVG file.

func (*AssetMin) GetMinifiedCSS added in v0.2.2

func (c *AssetMin) GetMinifiedCSS() ([]byte, error)

GetMinifiedCSS returns the minified content of the CSS bundle.

func (*AssetMin) GetMinifiedJS added in v0.2.2

func (c *AssetMin) GetMinifiedJS() ([]byte, error)

GetMinifiedJS returns the minified content of the JS bundle.

func (*AssetMin) GetSVGURLPath added in v0.2.2

func (c *AssetMin) GetSVGURLPath() string

GetSVGURLPath returns the URL path for the SVG sprite file.

func (*AssetMin) HasIcon added in v0.2.2

func (c *AssetMin) HasIcon(id string) bool

HasIcon checks if an icon with the given ID is registered.

func (*AssetMin) InjectCSS added in v0.0.81

func (c *AssetMin) InjectCSS(name string, content string)

AddCSS appends CSS content from providers to the bundle InjectCSS appends CSS content to the bundle. name is used for the virtual filename (e.g., "mycomponent.css"). AddCSS appends CSS content from providers to the bundle InjectCSS appends CSS content to the bundle. name is used for the virtual filename (e.g., "mycomponent.css").

func (*AssetMin) InjectHTML added in v0.0.81

func (c *AssetMin) InjectHTML(html string)

InjectHTML appends HTML to the body

func (*AssetMin) InjectJS added in v0.0.81

func (c *AssetMin) InjectJS(name string, content string)

AddJS appends JS content from providers to the bundle InjectJS appends JS content to the bundle. name is used for the virtual filename (e.g., "mycomponent.js").

func (*AssetMin) InjectSpriteIcon added in v0.0.81

func (c *AssetMin) InjectSpriteIcon(id, svg string) error

AddIcon adds icons from providers to the bundle InjectSpriteIcon adds an icon to the sprite bundle. id: unique icon ID. svg: raw SVG content.

func (*AssetMin) IsSSRMode added in v0.2.2

func (c *AssetMin) IsSSRMode() bool

IsSSRMode returns true if the package is being used as a dependency (SSR mode).

func (*AssetMin) Label added in v0.2.3

func (c *AssetMin) Label() string

Label returns the TUI button label reflecting current minification state.

func (*AssetMin) LoadSSRModules added in v0.2.2

func (c *AssetMin) LoadSSRModules()

LoadSSRModules descubre todos los módulos e inyecta sus assets (asíncrono).

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) RefreshJSAssets added in v0.2.7

func (c *AssetMin) RefreshJSAssets()

RefreshJSAssets triggers a refresh of JS assets. Call this when the WASM binary changes to ensure they are up to date.

func (*AssetMin) RegenerateHTMLCache added in v0.2.2

func (c *AssetMin) RegenerateHTMLCache() error

RegenerateHTMLCache forces regeneration of the HTML cache.

func (*AssetMin) RegisterComponents added in v0.2.2

func (c *AssetMin) RegisterComponents(providers ...any) error

RegisterComponents registra structs que implementan las interfaces SSR.

func (*AssetMin) RegisterRoutes

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

RegisterRoutes registers the HTTP handlers for all assets.

func (*AssetMin) ReloadSSRModule added in v0.2.2

func (c *AssetMin) ReloadSSRModule(moduleDir string) error

ReloadSSRModule re-extrae e inyecta los assets de un único módulo por su directorio.

func (*AssetMin) ScheduleSSRLoad added in v0.2.4

func (c *AssetMin) ScheduleSSRLoad()

ScheduleSSRLoad inicia la carga de módulos SSR en segundo plano de forma segura.

func (*AssetMin) SetBuildOnDisk added in v0.0.71

func (c *AssetMin) SetBuildOnDisk(onDisk bool)

SetBuildOnDisk sets the work mode for AssetMin. Deprecated: use SetExternalSSRCompiler instead to specify both callback and disk mode.

func (*AssetMin) SetExternalSSRCompiler added in v0.0.76

func (c *AssetMin) SetExternalSSRCompiler(fn func() error, buildOnDisk bool)

SetExternalSSRCompiler sets the external compiler trigger for SSR mode.

func (*AssetMin) SetListModulesFn added in v0.2.2

func (c *AssetMin) SetListModulesFn(fn func(rootDir string) ([]string, error))

SetListModulesFn replaces the module discovery function. Only for tests — allows injecting dummy directories without network.

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) TestOnly_ModuleSubpackagesUsed added in v0.2.3

func (c *AssetMin) TestOnly_ModuleSubpackagesUsed(modulePath, moduleDir string, importedPaths map[string]bool) []string

TestOnly_ModuleSubpackagesUsed is for testing the subpackage matcher.

func (*AssetMin) TestOnly_ScanImports added in v0.2.3

func (c *AssetMin) TestOnly_ScanImports() (map[string]bool, error)

TestOnly_ScanImports is for testing the import scanner.

func (*AssetMin) UnobservedFiles

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

func (*AssetMin) UpdateFileContentInMemory

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

func (*AssetMin) UpdateSSRModule added in v0.2.2

func (c *AssetMin) UpdateSSRModule(name string, css, js, html string, icons map[string]string)

UpdateSSRModule inyecta o reemplaza los assets de un módulo por nombre en el slot por defecto (middle).

func (*AssetMin) UpdateSSRModuleInSlot added in v0.2.2

func (c *AssetMin) UpdateSSRModuleInSlot(name string, css, js, html string, icons map[string]string, slot string)

UpdateSSRModuleInSlot inyecta o reemplaza los assets de un módulo en el slot especificado.

func (*AssetMin) WaitForSSRLoad added in v0.2.2

func (c *AssetMin) WaitForSSRLoad(timeout time.Duration)

WaitForSSRLoad espera a que LoadSSRModules termine, hasta el timeout dado.

type Config

type Config struct {
	OutputDir          string                 // eg: web/static, web/public, web/assets
	RootDir            string                 // Root directory of the project where go.mod exists
	GetSSRClientInitJS 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
	DevMode            bool                   // If true, disables caching (default: false)
}

type ContentFile added in v0.2.2

type ContentFile struct {
	Path    string // eg: modules/module1/file.js
	Content []byte /// eg: "console.log('hello world')"
}

ContentFile represents a file with its path and content

func (*ContentFile) WriteToDisk added in v0.2.2

func (f *ContentFile) WriteToDisk() error

WriteToDisk writes the content file to disk at the specified path It creates parent directories if they don't exist

type Module added in v0.2.2

type Module struct {
	Path string
	Dir  string
	Main bool
}

Module representa la salida de `go list -m -json all`

type ModuleAlias added in v0.3.0

type ModuleAlias struct {
	Path        string
	Alias       string
	HasInstance bool
	HasRoot     bool
	HasRender   bool
	HasHTML     bool
	HasJS       bool
	HasIcons    bool
}

func ModulesToAliases added in v0.3.0

func ModulesToAliases(modules []Module) []ModuleAlias

ModulesToAliases converts module information to alias mappings and detects features via regex.

type SSRAssets added in v0.2.2

type SSRAssets struct {
	ModuleName string
	RootCSS    string
	CSS        string
	JS         string
	HTML       string
	Icons      map[string]string
}

func ExtractSSRAssets added in v0.2.2

func ExtractSSRAssets(moduleDir string) (*SSRAssets, error)

ExtractSSRAssets uses compile-and-invoke to extract assets from a module. The module must be a proper Go module with go.mod and ssr.go files.

Jump to

Keyboard shortcuts

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