When developing websites, it's sometimes hard to find a nice balance between neatly organized development files and the final assets used in production. It is in general considered good practice to combine files into as few files as possible and minify them so as to limit the number and size of requests needed.
Tools such as Gulp or Grunt try to make this easy, but have a couple of caveats: these scripts can have quite a few dependencies, which are not always easy to install when developing with colleagues on varying platforms; these tools are not the easiest to configure; and these scripts must be manually run in order for the final assets to be updated.
Django Compressor, on the other hand, is a very handy module for Django which will combine and minify files included in your Django template. This saves you having to setup elaborate configuration files and manually running scripts. Just install it, include your files in your template between its template tags and reload your page.
{% load compressor %} {% compress css %} <link href="{% static 'css/main.css' %} {% endcompress %}
This allows you to include all your static files in a readable manor without having to add paths in some config file. They will be combined as soon as the page is refreshed or via the management command.
You can even directly include files that require preprocessors such as SASS, SCSS and coffeescript. In order to use preprocessors, you simply have to associate the desired mime type with the preprocessor command or python module in your Django settings.
For SCSS/SASS you may use the Ruby SASS command, but I prefer to use Django libsass as it can be included in your requirements file and installed with pip so you do not have to worry about manually installing anything.
COMPRESS_PRECOMPILERS = ( ('text/x-scss', 'django_libsass.SassCompiler'), ) LIBSASS_OUTPUT_STYLE = 'compressed'
Now you can include the files in your template directly. Just remember to specify the mime type in the link or script tag otherwise Django Compressor will assume they're a standard CSS or JavaScript file.
{% compress css %} <link rel="stylesheet" type="text/css" href="{% static 'vendor/materialize/css/materialize.min.css' %}"> <link rel="stylesheet" type="text/x-scss" href="{% static 'scss/main.scss' %}"> {% endcompress %}
If you so desire, you may also include in-line styles or scripts in the compress tag and they will also be included in the compressed file.
If you would like to have the output of Django Compressor included in the page instead of in an external file you may pass the argument "inline" to the template tag.
{% compress js inline %} <script src="{% static 'js/script.js' %}"></script> {% endcompress %}
Django compressor doesn't do everything Gulp and Grunt can do, but it has a lot of great features that are more than enough for most projects and help to simplify your workflow greatly.
Publier un commentaire.