Install this from pip:
$ pip install django-static-compress
(you may want to write this in your requirements.txt)
Then update your settings.py:
STATICFILES_STORAGE = 'static_compress.CompressedStaticFilesStorage'
When you run
python manage.py collectstatic it will have an additional post-processing pass to compress your static files.
Make sure that your web server is configured to serve precompressed static files:
- If using nginx:
- Caddy will serve .gz and .br without additional configuration.
Also, as Brotli is not supported by all browsers you should make sure that your reverse proxy/CDN honor the Vary header, and your web server set it to
.gzfrom your static files
ManifestStaticFilesStorage, but also generate compressed files for the hashed files
CachedStaticFilesStorage, but also generate compressed files for the hashed files
You can also add support to your own backend by applying
static_compress.CompressMixin to your class.
By default it will only compress files ending with
.svg. This is controlled by the settings below.
django-static-compress settings and their default values:
STATIC_COMPRESS_FILE_EXTS = ['js', 'css', 'svg'] STATIC_COMPRESS_METHODS = ['gz', 'br'] STATIC_COMPRESS_KEEP_ORIGINAL = True STATIC_COMPRESS_MIN_SIZE_KB = 30
After compressing the static files, django-static-compress still leaves the original files in STATIC_ROOT folder. If you want to delete (to save disk space), change
If the file is too small, it isn't worth compressing. You can change the minimum size in KiB at which file should be compressed, by changing
By default, django-static-compress use Zopfli to compress to gzip. Zopfli compress better than gzip, but will take more time to compress. If you want to create gzip file with built-in zlib compressor, replace
File size reduction
Here's some statistics from TipMe's jQuery and React bundle. Both bundle have related plugins built in with webpack (eg. Bootstrap for jQuery bundle, and classnames for React bundle), and is already minified.
101K jquery.9aa33728c6b5.js 33K jquery.9aa33728c6b5.js.gz (33%) 31K jquery.9aa33728c6b5.js.br (31%) 174K react.5c4899aeda53.js 51K react.5c4899aeda53.js.gz (29%) 44K react.5c4899aeda53.js.br (25%)
(.gz is Zopfli compressed, and .br is Brotli compressed)
To contribute to this project:
- Fork and clone this repository
python setup.py develop
pip install -r requirements-dev.txt && pre-commit install
- Start hacking
- Run test:
python setup.py test
- Run integration test:
cd integration_test; python manage.py test
- Commit. Pre-commit will warn if you have any changes.
- Submit pull request on GitHub
- Make sure Travis tests pass.
Licensed under the MIT License