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
Installation
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.
Usage
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" %} {% endassets %} {% assets "app_js" %} {% endassets %} {% assets "app_js_exts" %} {% 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.
Fantastic post however I was wondering if you
could write a little more on this topic? I’d be very
thankful if you could elaborate a little bit further.
Thanks!
Very nice, cheers mate!
Some truly superb posts on this web site, thanks for contribution.
Pretty! This has been a really wonderful article.
Many thanks for providing this info.
Admiring the dedication you put into your website and in depth information you present.
It’s great to come across a blog every once in a while that isn’t the same out of
date rehashed information. Great read! I’ve bookmarked your
site and I’m including your RSS feeds to my Google
account.
Thanks for finally talking about > Nadzweb.com
» Blog Archive » Minification of css and javascript
in Flask using Flask-assets < Liked it!
Very nice post. I just stumbled upon your blog and wished to say that I have really enjoyed surfing
around your blog posts.