How to Compress and Version CSS & JavaScript in Django

To compress and version CSS and JavaScript files in your Django project, use the Django Compressor package. Let's look at how to install, configure and use it.



Install django-compressor VIA the pip package manager like this:


pip install django-compressor



Now in your projects file under INSTALLED_APPS include the compressor package like this


   # packages


Further down the file, let's define some configuration options to establish the root of the cache files, whether to enable compression and potentially any precompilers to use.


# Django Compressor Settings

COMPRESS_ROOT = 'static/'


   ('text/coffeescript', 'coffee --compile --stdio'),
   #('text/less', 'lesscpy -X {infile} {outfile}'),
   #('text/x-scss', 'django_libsass.SassCompiler'),
   ('text/x-scss', 'pysass {infile} {outfile}'),
   #('text/x-scss', 'sass --scss {infile} {outfile}'),


For SCSS preprocessing I use pysass because I found the default program set-up by Django Compress returned errors. To install pysass with pip use the following command:


pip install pysass



To apply compression and versioning to your files when they change, locate where they are linked in your templates and do something similar to:


For JavaScript:


{% load compress %}
{% compress js %}
  <script src="/static/js/app.js" type="text/javascript" charset="utf-8"></script>
{% endcompress %}




{% load compress %}
{% compress css %}
  <link rel="stylesheet" type="text/css" href="/static/css/all.css">
  <link rel="stylesheet" type="text/css" href="/static/css/app.css">
{% endcompress %}


The key point is to specify the type attribute, especially if you are using a precompiler as this tells Django Compress how to handle the file.


When using SCSS, you would need to specify the type when linking the file like this:


<link rel="stylesheet" type="text/scss" href="/static/css/all.scss">