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.

 

Installation

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

 

pip install django-compressor

 

Configuration

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

 

my_project/settings.py
INSTALLED_APPS = [
    ...
   # packages
   "compressor",
   ...
]

 

Further down the settings.py 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.

 

my_project/settings.py
# Django Compressor Settings

COMPRESS_ROOT = 'static/'

COMPRESS_ENABLED = False

COMPRESS_PRECOMPILERS = (
   ('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

 

Usage

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 %}

 

For CSS

 

{% 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">