Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minify Javascript programmatically in-memory

I am building a nifty little "asset-pipeline" for a express.js application, but i have a problem with the compression-step for javascript files

scripts = (fs.readFileSync(file) for file in filelist)
result = scripts.join("\n\n") # concat

upto now, things are working as expected (the logic itself is written in coffeescript). The next step after merging the JS-files would be to minify them. But here is my problem: i want to do this "hot" when i start my express-app in production mode, from within a piece of connect-middleware i wrote.

I need a solution that can minify a given blob of javascript stuff, without writing the result to disk (!), in other words: a function that does the minification and returns the result directly as a result value. (No, no webservices either.) It should be usable like this:

minified_result = awesomeMinifyFunction( result )

The raw processing performance isn't that important for me, neither is the level of compression, i need just something that works this way without hassle.

Does anyone know a suitable solution? Thanks in advance!

like image 873
Maximilian Stroh Avatar asked Mar 22 '23 09:03

Maximilian Stroh


1 Answers

I'd suggest you look at one of the JavaScript based minifiers, like UglifyJS2.

npm install uglify-js

It can be used within a Node.JS application programatically:

var UglifyJS = require("uglify-js");
// you could pass multiple files (rather than reading them as strings)
var result = UglifyJS.minify([ "file1.js", "file2.js", "file3.js" ]);
console.log(result.code);

Or you could

var result = scripts.join("\n\n");  # concat
result = UglifyJS.minify(result, {fromString: true});
console.log(result.code);
like image 128
WiredPrairie Avatar answered Apr 10 '23 04:04

WiredPrairie