CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-webassets

Media asset management for Python, with glue code for various web frameworks

Overview
Eval results
Files

bundle-management.mddocs/

Bundle Management

Core functionality for creating, configuring, and managing asset bundles that group related files together for processing and optimization.

Capabilities

Bundle Creation and Configuration

Create bundles to group related assets with processing options and output configuration.

class Bundle:
    def __init__(self, *contents, **options):
        """
        Create a new bundle.
        
        Parameters:
        - contents: Input files, URLs, or nested bundles
        - env: Environment instance to bind to
        - output: Output filename pattern (with optional %(version)s placeholder)
        - filters: Filter names or instances to apply during processing
        - depends: Additional dependency files for change detection
        - version: Version string or callable for cache busting
        - remove_duplicates: Remove duplicate files (default: True)
        - extra: Extra metadata dictionary
        - merge: Enable/disable file merging (default: True)
        - config: Bundle-specific configuration overrides
        - debug: Bundle-specific debug mode setting
        """

Example usage:

from webassets import Bundle

# Simple bundle with filters
js_bundle = Bundle(
    'lib/jquery.js',
    'app.js',
    'utils.js',
    filters='jsmin',
    output='gen/app.js'
)

# Bundle with version and dependencies
css_bundle = Bundle(
    'base.css',
    'theme.css',
    filters=['cssmin', 'cssrewrite'],
    output='gen/styles-%(version)s.css',
    depends=['variables.scss', 'config.json']
)

# Nested bundles
combined = Bundle(
    js_bundle,
    Bundle('vendor/lib1.js', 'vendor/lib2.js'),
    output='gen/all.js'
)

Bundle Building and Processing

Process bundles to generate optimized output files with filtering and optimization.

def build(self, force=None, output=None, disable_cache=None):
    """
    Build the bundle by processing all input files through filters.
    
    Parameters:
    - force: Force rebuild even if cache is valid (bool)
    - output: Override output filename
    - disable_cache: Disable caching for this build
    
    Returns:
    List of generated output files
    """

def urls(self, *args, **kwargs):
    """
    Get URLs for bundle output files.
    
    Returns:
    List of URL strings for accessing built assets
    """

def iterbuild(self, ctx):
    """
    Iterator for the build process, yielding intermediate steps.
    
    Parameters:
    - ctx: Build context
    
    Yields:
    Build steps and intermediate results
    """

Example usage:

# Build bundle
output_files = bundle.build()
print(f"Built files: {output_files}")

# Get URLs for templates
urls = bundle.urls()
for url in urls:
    print(f"<script src='{url}'></script>")

# Force rebuild
bundle.build(force=True)

# Build with custom output
bundle.build(output='custom-name.js')

Bundle Environment Binding

Bind bundles to environments for configuration inheritance and management.

def bind(self, env):
    """
    Bind this bundle to an environment.
    
    Parameters:
    - env: Environment instance
    
    Returns:
    Self for method chaining
    """

Example usage:

from webassets import Environment, Bundle

env = Environment('./static', '/static')
bundle = Bundle('app.js', filters='jsmin', output='gen/app.js')

# Bind bundle to environment
bundle.bind(env)

# Bundle now inherits environment configuration
bundle.build()

Bundle Content Resolution

Resolve bundle contents to actual files and handle dependency tracking.

def resolve_contents(self, ctx=None, force=False):
    """
    Resolve all input contents to actual file paths.
    
    Parameters:
    - ctx: Resolution context
    - force: Force re-resolution
    
    Returns:
    List of resolved file paths
    """

def resolve_output(self, ctx=None, version=None):
    """
    Resolve output filename, including version placeholder.
    
    Parameters:
    - ctx: Resolution context  
    - version: Version string to use
    
    Returns:
    Resolved output filename
    """

def get_version(self, ctx=None, refresh=False):
    """
    Get version string for this bundle.
    
    Parameters:
    - ctx: Context for version calculation
    - refresh: Force version recalculation
    
    Returns:
    Version string for cache busting
    """

def id(self):
    """
    Get unique identifier for this bundle.
    
    Returns:
    String identifier based on bundle configuration
    """

def iterbuild(self, ctx):
    """
    Generator that yields build steps for this bundle.
    
    Parameters:
    - ctx: Build context
    
    Yields:
    Build step information during bundle processing
    """

Bundle Properties and State

Access bundle configuration, contents, and processing state.

# Properties
@property
def config(self):
    """Bundle configuration storage"""

@property 
def debug(self):
    """Debug mode setting"""

@property
def filters(self):
    """Applied filters list"""

@property
def contents(self):
    """Input contents list"""

@property
def extra(self):
    """Extra metadata dictionary"""

@property
def id(self):
    """Bundle identifier"""

@property
def is_container(self):
    """Whether bundle contains other bundles"""

@property  
def env(self):
    """Associated environment"""

Bundle Utility Functions

Helper functions for working with bundles and their files.

def get_all_bundle_files(bundle, ctx=None):
    """
    Get all files used by a bundle, including dependencies.
    
    Parameters:
    - bundle: Bundle instance
    - ctx: Context for resolution
    
    Returns:
    Set of all file paths used by the bundle
    """

def has_placeholder(value):
    """
    Check if string contains version placeholder %(version)s.
    
    Parameters:
    - value: String to check
    
    Returns:
    bool: True if contains %(version)s placeholder
    """

Example usage:

from webassets import get_all_bundle_files

# Get all files in bundle
all_files = get_all_bundle_files(my_bundle)
print(f"Bundle uses {len(all_files)} files: {all_files}")

# Check bundle properties
print(f"Bundle ID: {bundle.id}")
print(f"Is container: {bundle.is_container}")
print(f"Debug mode: {bundle.debug}")
print(f"Filters: {bundle.filters}")

Bundle Configuration Classes

Supporting classes for bundle configuration and context management.

class BundleConfig:
    """Configuration dictionary with Environment-like attribute access."""

class ContextWrapper:
    """Hierarchy-aware configuration context for bundles."""
    
    def __init__(self, parent, overwrites=None): ...
    def __getitem__(self, key): ...
    def __getattr__(self, item): ...

def wrap(parent, overwrites):
    """
    Create context wrapper with parent and override configurations.
    
    Parameters:
    - parent: Parent configuration context
    - overwrites: Override configuration values
    
    Returns:
    ContextWrapper instance
    """

Advanced Usage Examples

Conditional Bundle Building

# Build only if needed
if bundle.get_version() != cached_version:
    bundle.build()
    
# Build with environment-specific settings
if env.debug:
    bundle.build(disable_cache=True)
else:
    bundle.build()

Complex Bundle Hierarchies

# Create vendor bundle
vendor_js = Bundle(
    'vendor/jquery.js',
    'vendor/bootstrap.js',
    filters='jsmin',
    output='gen/vendor.js'
)

# Create app bundle  
app_js = Bundle(
    'src/app.js',
    'src/utils.js',
    filters=['babel', 'jsmin'],
    output='gen/app.js'
)

# Combine into master bundle
master_bundle = Bundle(
    vendor_js,
    app_js,
    output='gen/combined.js'
)

Dynamic Bundle Creation

def create_theme_bundle(theme_name):
    return Bundle(
        f'themes/{theme_name}/base.css',
        f'themes/{theme_name}/components.css',
        filters='cssmin',
        output=f'gen/theme-{theme_name}.css'
    )

# Create theme-specific bundles
light_theme = create_theme_bundle('light')
dark_theme = create_theme_bundle('dark')

Install with Tessl CLI

npx tessl i tessl/pypi-webassets

docs

bundle-management.md

caching-versioning.md

command-line.md

configuration-loading.md

environment-configuration.md

filter-system.md

framework-integration.md

index.md

merge-system.md

updater-system.md

utilities.md

tile.json