Tech
Infected

Linux, OpenSource, Programming And Hacks

Mar 2, 2018

Minify JavaScript / CSS with Django Compressor

Mar 2, 2018

Django Compressor minifies JavaScript and CSS files. It can combine several inline or linked files into cacheable static files. it also supports uglify wih yuglify compressor

Install Django Compressor


pip install django_compressor

In your settings.py

INSTALLED_APPS = (
    # Add compressor to the installed apps
    "compressor",
)

COMPRESS_ENABLED = True

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    # other finders..
    'compressor.finders.CompressorFinder',
)

COMPRESS_ENABLED = True

#add filters
 
COMPRESS_CSS_FILTERS = [
    'compressor.filters.cssmin.CSSMinFilter'
]
COMPRESS_JS_FILTERS = [
    'compressor.filters.jsmin.JSMinFilter'
]


Usage

{% load compress %} 
{% compress css %}
<link rel="stylesheet" href="/static/css/example.css" type="text/css">
<style>p { font-size:5px; color:green;}</style>
<link rel="stylesheet" href="/static/css/example2.css" type="text/css" charset="utf-8">
{% endcompress %}

{% compress js %}
<script src="/static/js/example.js"></script>
<script> console.log("some msg"); function sample() { console.log("some function definition") }</script>
{% endcompress %}

Result:
<link rel="stylesheet" href="/static/CACHE/css/07786f58by27.css" type="text/css" />
<script type="text/javascript" src="/static/CACHE/js/70850ie6975h.js"></script>

Note: Make sure static root is defined or you will get an error something like this
django.core.exceptions.ImproperlyConfigured: COMPRESS_ROOT defaults to STATIC_ROOT, please define either




No comments:

Post a Comment