Minification of css and javascript in Flask using Flask-assets

Flask is a minimal python based web framework for building enterprise like applications. In my current project, I am using Flask for development. The project is nearly complete but I have yet to do minification of static assets. I have used Flask-assets, an extension for Flask to minify the static assets.

Below is a step by step guide


To install Flask-Assets, run the command (inside your virtualenv) pip install flask-assets jsmin cssmin. This will install jsmin, cssmin and flask-assets. Jsmin and cssmin are minification tools for javascript and css respectively.


The below is a guide to implementing flask-assets.

  • Import the extension in flask application.
    from flask.ext.assets import Environment, Bundle
  • Initialize the current application namely app
    assets = Environment(app)
    assets.versions = 'timestamp'
  • Minify css using cssmin filter and output it as nadzweb.min.css file in the /static/ folder.
    app_css = Bundle('style.css', 'jquery.tableless.css',
                   filters='cssmin', output='nadzweb.min.css')
  • Minify javascript using jsmin filter and output it in /static/ folder. It is recommended to minify all plugins in one file and include a compressed version of the library into another. As seen in the code below, all jquery extensions are compressed into nadzweb.ext.min.js.
    app_js_exts = Bundle('js/jquery.colorchange.js', 'js/jquery.iframe-transport.js',
                       filters='jsmin', output='nadzweb.ext.min.js')
    app_js = Bundle('js/nadzweb.js', filters='jsmin', output='nadzweb.min.js')
  • Register the assets for the app
    assets.register('app_css', app_css)
    assets.register('app_js', app_js)
    assets.register('app_js_exts', app_js_exts)
  • Display the compressed file in the template, e.g. header.tpl

    {% assets "app_css" %}
       <link type="text/css" href="{{ ASSET_URL }}" rel="stylesheet">
    {% endassets %}
    {% assets "app_js" %}
        <script type="text/javascript" src="{{ ASSET_URL }}"></script>
    {% endassets %}
    {% assets "app_js_exts" %}
        <script type="text/javascript" src="{{ ASSET_URL }}"></script>
    {% endassets %}

** Note: Make sure that flask owner has write permission to /static/ folder. Webassets cache files are generated in /static/.webassets-cache folder.

Advanced configurations can be found at Flask-assets and Webassets website.


Add a Comment

Your email address will not be published. Required fields are marked *

To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image