Precompile Assets with Flask-Assets

I want to re-compile static assets (SASS to CSS and Coffeescript to JS) whenever there’s change in my Flask app.

I also want to optionally set a flag to toggle whether that compilation happens or not.

I’m using Flask-Assets, and it only seems to trigger the compilation whenever the jinja template with the corresponding assets extension is loaded.

For example, js_all.js will only be created whenever the jinja template with the following is loaded.

{% assets "js_all" %}
    <script type="text/javascript" src="{{ ASSET_URL }}"></script>
{% endassets %}

Bizarrely, triggering the build manually was rather hard to search for.

Here’s my solution.

****Update****
You can use bundle.build() instead of asserts[‘js_all’].urls()

if reload_flag:
  assets = Environment(app)

  # Don't cache otherwise it won't build every time
  assets.cache = False
  assets.manifest = False

  js = Bundle('jquery.js', 'base.js', 'widgets.js',
              filters='jsmin', output='gen/packed.js')
  assets.register('js_all', js)

  js.build()

****

You can build bundles manually with .urls().

if reload_flag:
  assets = Environment(app)

  js = Bundle('jquery.js', 'base.js', 'widgets.js',
              filters='jsmin', output='gen/packed.js')
  assets.register('js_all', js)

  assets['js_all'].urls()

In the template:

<script type="text/javascript" src="/static/gen/js_all.js"></script>

It’s a lot less robust than using assets to automatically inject the resource url, but for me, I don’t want compilation to happen on production (I don’t even want the compilation tools on the production machines).

Hope this helps folks.
Let me know if there’s a better answer.

Advertisements
1 comment
  1. You should add some extra code to search for files to bundle up, instead of explicitly specifying files. (I believe there’s a better package that does this, but I’m forgetting its name)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: