Web development can be tedious at times, so any tool that can relieve repetition and enable more concise coding is a welcome addition to the belt. LESS and CoffeeScript make CSS and JavaScript a whole lot more pleasant to write and therefore it is natural to want to incorporate it in your Django project. However, it takes a little leg work to make it happen, and a little more fiddling when wanting to run it on Heroku.
Step 1: Install django-compressor
The Django Compressor documentation provides a nice introduction which I have summarized and commented on here.
Install using pip.
$ pip install django_compressor
Add 'compressor' to INSTALLED_APPS
in settings.py
and add compressor.finders.CompressorFinder
to STATICFILES_FINDERS
. We then need to enable compression and then specify which pre-compilers we wish to use. The pre-compilation is the interesting part for LESS and CoffeeScript -- the first elements in the tuples in COMPRESS_PRECOMPILERS
will be checked against the type attributes of scripts in compress template tags.
# settings.py INSTALLED_APPS = ( # other apps 'compressor', ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # other finders.. 'compressor.finders.CompressorFinder', ) COMPRESS_ENABLED = True COMPRESS_PRECOMPILERS = ( ('text/coffeescript', 'coffee --compile --stdio'), ('text/less', 'lessc {infile} {outfile}'), )
Step 2: Install CoffeeScript and LESS
Both CoffeeScript and LESS are compiled using node.js and must be installed using npm. If node.js is not already installed it can be downloaded here.
$ npm install -g coffee-script $ npm install -g less
Step 3: Apply template tags
After following step 1 and 2 it is now possible to include .less and .coffee files in any Django template. We just need to load the compress module and embed the HTML tags in the appropriate template tags.
{% load compress %} {% compress css %} <link type="text/less" rel="stylesheet" charset="utf-8" href="{{ STATIC_URL }}css/example.less" /> {% endcompress %} {% compress js %} <script type="text/coffeescript" charset="utf-8" src="{{ STATIC_URL }}js/example.coffee" /> {% endcompress %}
Step 4: Run on Heroku
Since CoffeeScript and LESS installation, as described in step 3, require npm to be installed, we run into trouble when deploying on Heroku. Luckily @Jiaaro provides us with the solution in this StackOverflow answer. We need to add a buildpack to our Heroku configuration and create a npm_requirements.txt
file specifying the modules we need.
This command will configure the Heroku configuration.
$ heroku config:add BUILDPACK_URL=git://github.com/jiaaro/heroku-buildpack-django.git
And the following should be the content of our npm_requirements.txt
.
coffee-script less
And that's it.