Compressing and merging static files into bundles with webassets
Compressed files have slightly smaller size and they load faster. One file made out of multiple CSS or JS files reduces the amount of HTTP requests needed to load the website. That also improves the load times.
Installation is typical - pip install webassets. If you want to use it with Django, you need to add django_assets to INSTALLED_APPS. Next you create a assets.py file in one of your applications (like the main app holding your base templates or base views). In this file we define bundles of given type files. Here is an example:
Bundle takes a collection of files to bundle (each file type need their own bundle), a filter (or filters) to apply to those files and the output file with path. Every path is relative to STATIC_ROOT or static folders of your apps for dev-server. The list of filters for JS, CSS and other files (like LESS files which can be parsed to CSS) are listed in the documentation. Some of them require additional packages to be installed.
When you have your bundles defined you can use them in a template:
And that's it. In this example the whole JS code from three files got merged into one and compressed. Webassets will create a new file every time something changes in the bundled files. It will also change the version "number" added to the filename so users won't get cached old version.
If you have tests then you have to call collectstatic before starting them. Bundle will raise an exception if it can't find a file needed for the bundle. collectstatic will provide all static files (tests use debug=False so static files must be collected).
In case of style sheets you may need cssrewrite to update image paths used in those files.