Python modules you should know: SlimIt

April 30, 2012 at 07:10 AM | categories: Python, PyMYSK, Howto | View Comments

Next in our series of Python modules you should know is SlimIt. I previously wrote about the minification of CSS files, the Slimit package is used for minification of Javascript files.

Home page

Use

SlimIt is a JavaScript minifier written in Python. It compiles JavaScript into more compact code so that it downloads and runs faster.

SlimIt also provides a library that includes a JavaScript parser, lexer, pretty printer and a tree visitor.

Installation

pip install slimit

Usage

The package provides a command line interface as well as Python functions.

Python functions

Minify Javascript

from slimit import minify
minified = minify(open('jquery-1.7.2.js').read(), mangle=True, mangle_toplevel=True)
print minified

Modify Javascript within Python and beautify it

This example is taken directly from the documentation. It modifies the counter variable changing it from "i" to "hello" and formats it in a more readable style.

from slimit.parser import Parser
from slimit.visitors import nodevisitor
from slimit import ast

parser = Parser()
tree = parser.parse('for(var i=0; i<10; i++) {var x=5+i;}')
for node in nodevisitor.visit(tree):
    if isinstance(node, ast.Identifier) and node.value == 'i':
        node.value = 'hello'
print tree.to_ecma()

Output:

for (var hello = 0; hello < 10; hello++) {
  var x = 5 + hello;
}

Command line

slimit --mangle < jquery-1.7.2.js > jquery-1.7.2.slimit.default.js

Performance

The performance is very good, most times it creates smaller files than the YUI compresser. I tested minifying Jquery using 3 javascript minification tools:

  • jsmin
  • yuicompressor
  • slimit

The results are below.

-rw-r--r--  1 andrew  staff   247K Mar 21 21:46 jquery-1.7.2.js
-rw-r--r--  1 andrew  staff   138K Apr 30 08:26 jquery-1.7.2.jsmin.js
-rw-r--r--  1 andrew  staff    96K Apr 30 08:22 jquery-1.7.2.slimit.js
-rw-r--r--  1 andrew  staff   103K Apr 30 08:19 jquery-1.7.2.yui.js

And there is more

Slimit also exposes JavaScript parser and lexer functions which you can use within your code, please refer to the documentation for usage information.


blog comments powered by Disqus