Webassets

3.0.0 · active · verified Thu Apr 16

Webassets is a general, dependency-independent library for managing the assets of your web application, compatible with Python 3.10 and later. It efficiently merges and compresses CSS and JavaScript files, supports various filters, and integrates with compilers like CoffeeScript or Sass. The library currently stands at version 3.0.0 and has an active development cadence, with recent major updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `webassets` in a standalone Python application. It initializes an `Environment`, defines `Bundle`s for CSS and JavaScript, registers them, and then prints the generated URLs in both production (merged/filtered) and debug (individual files) modes. This example includes a basic cleanup of temporary files.

import os
import shutil
from webassets import Environment, Bundle

# Define base directories and create dummy files for demonstration
base_dir = "webassets_quickstart_temp"
static_dir = os.path.join(base_dir, "static")
css_dir = os.path.join(static_dir, "css")
js_dir = os.path.join(static_dir, "js")
output_dir = os.path.join(static_dir, "gen")

os.makedirs(css_dir, exist_ok=True)
os.makedirs(js_dir, exist_ok=True)
os.makedirs(output_dir, exist_ok=True)

with open(os.path.join(css_dir, "style.css"), "w") as f:
    f.write("body { font-family: sans-serif; }\n")
with open(os.path.join(js_dir, "main.js"), "w") as f:
    f.write("console.log('Hello from main.js');\n")
with open(os.path.join(js_dir, "utils.js"), "w") as f:
    f.write("function greet() { return 'Greetings!'; }\n")

# Initialize the Environment
# `directory` is the base path for source files and output
# `url` is the base URL from which assets are served in the browser
env = Environment(directory=static_dir, url='/static')

# Define a CSS bundle (no filters for simplicity in this quickstart)
css_bundle = Bundle(
    'css/style.css',
    output='gen/packed.css'
)

# Define a JavaScript bundle with an included filter (rjsmin)
js_bundle = Bundle(
    'js/main.js',
    'js/utils.js',
    filters='rjsmin', # rjsmin is included with webassets
    output='gen/packed.js'
)

# Register bundles with the environment
env.register('all_css', css_bundle)
env.register('all_js', js_bundle)

# Access the URLs in production mode (default behaviour: merges and applies filters)
print("CSS URLs (production mode):", env['all_css'].urls())
print("JS URLs (production mode):", env['all_js'].urls())

# Switch to debug mode to see individual source files (for development)
env.debug = True
print("\nCSS URLs (debug mode):", env['all_css'].urls())
print("JS URLs (debug mode):", env['all_js'].urls())

# Clean up dummy files and directories
shutil.rmtree(base_dir)

view raw JSON →