Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the Jade template compress inline javascript automatically?

Tags:

node.js

pug

when I check the html page source, the HTML tags and text content are compressed without blank and line, but inline javascript.

like image 478
mockee Avatar asked Aug 11 '11 09:08

mockee


3 Answers

Just discovered something that works for me in Jade v0.30.0:

  1. Rename your .js file with a .uglify extension
  2. In your Jade template, use:

    include name-of-javascript-file.uglify
    

Why it works: Digging into the Jade source code, I discovered a file called filters.js. In there, you'll see a dependency on transformers. In lib/transformers.js (of the transformers module), you will see the various transform utilities, including uglify. Apparently, Jade will call on any of those transformers if you match the right file extension in your include declaration.

like image 138
joefru Avatar answered Nov 15 '22 02:11

joefru


I'm not sure about it and haven't tested it yet, but you can probalby add a filter and utilize UglifyJS. For example

var uglyParser = require("uglify-js").parser;
var uglyUgly   = require("uglify-js").uglify;

var uglify = function(str) {
  var ast = uglyParser.parse(str);
  ast = uglyUgly.ast_mangle(ast);
  ast = uglyUgly.ast_squeeze(ast);
  return uglyUgly.gen_code(ast);
}

To be honest, I'm not sure where to put that in jade so it's treated as a filter. For now you should be able to just stick it at https://github.com/visionmedia/jade/blob/master/lib/filters.js.

The usage in jade would then be:

script(type="text/javascript")
  :uglify
    <Your JavaScript Code>

Again I haven't tested it. But I think it should work. I'll test it later today.

like image 37
mck Avatar answered Nov 15 '22 04:11

mck


According to the docs, you can use any JSTransformer as a jade filter. So, where you would normally do this to inline JS:

script.
  (function doSomething () { … })();

you should do it like this:

script
  :uglify-js
    (function doSomething () { … })();
like image 28
Alfonso Avatar answered Nov 15 '22 04:11

Alfonso