0
# Bundle Management
1
2
Core functionality for creating, configuring, and managing asset bundles that group related files together for processing and optimization.
3
4
## Capabilities
5
6
### Bundle Creation and Configuration
7
8
Create bundles to group related assets with processing options and output configuration.
9
10
```python { .api }
11
class Bundle:
12
def __init__(self, *contents, **options):
13
"""
14
Create a new bundle.
15
16
Parameters:
17
- contents: Input files, URLs, or nested bundles
18
- env: Environment instance to bind to
19
- output: Output filename pattern (with optional %(version)s placeholder)
20
- filters: Filter names or instances to apply during processing
21
- depends: Additional dependency files for change detection
22
- version: Version string or callable for cache busting
23
- remove_duplicates: Remove duplicate files (default: True)
24
- extra: Extra metadata dictionary
25
- merge: Enable/disable file merging (default: True)
26
- config: Bundle-specific configuration overrides
27
- debug: Bundle-specific debug mode setting
28
"""
29
```
30
31
Example usage:
32
```python
33
from webassets import Bundle
34
35
# Simple bundle with filters
36
js_bundle = Bundle(
37
'lib/jquery.js',
38
'app.js',
39
'utils.js',
40
filters='jsmin',
41
output='gen/app.js'
42
)
43
44
# Bundle with version and dependencies
45
css_bundle = Bundle(
46
'base.css',
47
'theme.css',
48
filters=['cssmin', 'cssrewrite'],
49
output='gen/styles-%(version)s.css',
50
depends=['variables.scss', 'config.json']
51
)
52
53
# Nested bundles
54
combined = Bundle(
55
js_bundle,
56
Bundle('vendor/lib1.js', 'vendor/lib2.js'),
57
output='gen/all.js'
58
)
59
```
60
61
### Bundle Building and Processing
62
63
Process bundles to generate optimized output files with filtering and optimization.
64
65
```python { .api }
66
def build(self, force=None, output=None, disable_cache=None):
67
"""
68
Build the bundle by processing all input files through filters.
69
70
Parameters:
71
- force: Force rebuild even if cache is valid (bool)
72
- output: Override output filename
73
- disable_cache: Disable caching for this build
74
75
Returns:
76
List of generated output files
77
"""
78
79
def urls(self, *args, **kwargs):
80
"""
81
Get URLs for bundle output files.
82
83
Returns:
84
List of URL strings for accessing built assets
85
"""
86
87
def iterbuild(self, ctx):
88
"""
89
Iterator for the build process, yielding intermediate steps.
90
91
Parameters:
92
- ctx: Build context
93
94
Yields:
95
Build steps and intermediate results
96
"""
97
```
98
99
Example usage:
100
```python
101
# Build bundle
102
output_files = bundle.build()
103
print(f"Built files: {output_files}")
104
105
# Get URLs for templates
106
urls = bundle.urls()
107
for url in urls:
108
print(f"<script src='{url}'></script>")
109
110
# Force rebuild
111
bundle.build(force=True)
112
113
# Build with custom output
114
bundle.build(output='custom-name.js')
115
```
116
117
### Bundle Environment Binding
118
119
Bind bundles to environments for configuration inheritance and management.
120
121
```python { .api }
122
def bind(self, env):
123
"""
124
Bind this bundle to an environment.
125
126
Parameters:
127
- env: Environment instance
128
129
Returns:
130
Self for method chaining
131
"""
132
```
133
134
Example usage:
135
```python
136
from webassets import Environment, Bundle
137
138
env = Environment('./static', '/static')
139
bundle = Bundle('app.js', filters='jsmin', output='gen/app.js')
140
141
# Bind bundle to environment
142
bundle.bind(env)
143
144
# Bundle now inherits environment configuration
145
bundle.build()
146
```
147
148
### Bundle Content Resolution
149
150
Resolve bundle contents to actual files and handle dependency tracking.
151
152
```python { .api }
153
def resolve_contents(self, ctx=None, force=False):
154
"""
155
Resolve all input contents to actual file paths.
156
157
Parameters:
158
- ctx: Resolution context
159
- force: Force re-resolution
160
161
Returns:
162
List of resolved file paths
163
"""
164
165
def resolve_output(self, ctx=None, version=None):
166
"""
167
Resolve output filename, including version placeholder.
168
169
Parameters:
170
- ctx: Resolution context
171
- version: Version string to use
172
173
Returns:
174
Resolved output filename
175
"""
176
177
def get_version(self, ctx=None, refresh=False):
178
"""
179
Get version string for this bundle.
180
181
Parameters:
182
- ctx: Context for version calculation
183
- refresh: Force version recalculation
184
185
Returns:
186
Version string for cache busting
187
"""
188
189
def id(self):
190
"""
191
Get unique identifier for this bundle.
192
193
Returns:
194
String identifier based on bundle configuration
195
"""
196
197
def iterbuild(self, ctx):
198
"""
199
Generator that yields build steps for this bundle.
200
201
Parameters:
202
- ctx: Build context
203
204
Yields:
205
Build step information during bundle processing
206
"""
207
```
208
209
### Bundle Properties and State
210
211
Access bundle configuration, contents, and processing state.
212
213
```python { .api }
214
# Properties
215
@property
216
def config(self):
217
"""Bundle configuration storage"""
218
219
@property
220
def debug(self):
221
"""Debug mode setting"""
222
223
@property
224
def filters(self):
225
"""Applied filters list"""
226
227
@property
228
def contents(self):
229
"""Input contents list"""
230
231
@property
232
def extra(self):
233
"""Extra metadata dictionary"""
234
235
@property
236
def id(self):
237
"""Bundle identifier"""
238
239
@property
240
def is_container(self):
241
"""Whether bundle contains other bundles"""
242
243
@property
244
def env(self):
245
"""Associated environment"""
246
```
247
248
### Bundle Utility Functions
249
250
Helper functions for working with bundles and their files.
251
252
```python { .api }
253
def get_all_bundle_files(bundle, ctx=None):
254
"""
255
Get all files used by a bundle, including dependencies.
256
257
Parameters:
258
- bundle: Bundle instance
259
- ctx: Context for resolution
260
261
Returns:
262
Set of all file paths used by the bundle
263
"""
264
265
def has_placeholder(value):
266
"""
267
Check if string contains version placeholder %(version)s.
268
269
Parameters:
270
- value: String to check
271
272
Returns:
273
bool: True if contains %(version)s placeholder
274
"""
275
```
276
277
Example usage:
278
```python
279
from webassets import get_all_bundle_files
280
281
# Get all files in bundle
282
all_files = get_all_bundle_files(my_bundle)
283
print(f"Bundle uses {len(all_files)} files: {all_files}")
284
285
# Check bundle properties
286
print(f"Bundle ID: {bundle.id}")
287
print(f"Is container: {bundle.is_container}")
288
print(f"Debug mode: {bundle.debug}")
289
print(f"Filters: {bundle.filters}")
290
```
291
292
### Bundle Configuration Classes
293
294
Supporting classes for bundle configuration and context management.
295
296
```python { .api }
297
class BundleConfig:
298
"""Configuration dictionary with Environment-like attribute access."""
299
300
class ContextWrapper:
301
"""Hierarchy-aware configuration context for bundles."""
302
303
def __init__(self, parent, overwrites=None): ...
304
def __getitem__(self, key): ...
305
def __getattr__(self, item): ...
306
307
def wrap(parent, overwrites):
308
"""
309
Create context wrapper with parent and override configurations.
310
311
Parameters:
312
- parent: Parent configuration context
313
- overwrites: Override configuration values
314
315
Returns:
316
ContextWrapper instance
317
"""
318
```
319
320
## Advanced Usage Examples
321
322
### Conditional Bundle Building
323
324
```python
325
# Build only if needed
326
if bundle.get_version() != cached_version:
327
bundle.build()
328
329
# Build with environment-specific settings
330
if env.debug:
331
bundle.build(disable_cache=True)
332
else:
333
bundle.build()
334
```
335
336
### Complex Bundle Hierarchies
337
338
```python
339
# Create vendor bundle
340
vendor_js = Bundle(
341
'vendor/jquery.js',
342
'vendor/bootstrap.js',
343
filters='jsmin',
344
output='gen/vendor.js'
345
)
346
347
# Create app bundle
348
app_js = Bundle(
349
'src/app.js',
350
'src/utils.js',
351
filters=['babel', 'jsmin'],
352
output='gen/app.js'
353
)
354
355
# Combine into master bundle
356
master_bundle = Bundle(
357
vendor_js,
358
app_js,
359
output='gen/combined.js'
360
)
361
```
362
363
### Dynamic Bundle Creation
364
365
```python
366
def create_theme_bundle(theme_name):
367
return Bundle(
368
f'themes/{theme_name}/base.css',
369
f'themes/{theme_name}/components.css',
370
filters='cssmin',
371
output=f'gen/theme-{theme_name}.css'
372
)
373
374
# Create theme-specific bundles
375
light_theme = create_theme_bundle('light')
376
dark_theme = create_theme_bundle('dark')
377
```