Use Google Closure Compiler Local with PHP

Posted by Fichtl on 11.09.2010

 

First download and unpack the Closure java application to your computer or your server, the download url is:  http://closure-compiler.googlecode.com/files/compiler-latest.zip 

On linux servers you can do the download with wget: 

wget http://closure-compiler.googlecode.com/files/compiler-latest.zip  unzip compiler-latest.zip

After unpacking you get a file named compiler.jar, that's the application, you can execute it only if you have java installed. If not, see the help page for installing java on debian servers.  

java -jar compiler.jar --js hello.js --js_output_file hello-compiled.js  

The command above compiles a hello.js in the current working directory to hello-compiled.js with the default settings. For more infos you can show a help screen with:  

java -jar compiler.jar --help

Usually you want compile your whole scripts directory. My script reads all files of a given directory, checks if the file is a .js and compiles it to another directory:  

$basePath = dirname(__FILE__); $scriptDir = $basePath.'/scripts/'; $compiledDir = $basePath.'/compiled/'; if (is_dir($scriptDir)) { if ($dh = opendir($scriptDir)) { while (($file = readdir($dh)) !== false) { // read all files, if file is js and not minified then minify/compile it if (strpos($file, '.js') !== false && strpos($file, '.min.js') === false) { $compilerCommand = sprintf('/usr/bin/java -jar %s/compiler.jar --js %s --js_output_file %s', $basePath, $scriptDir.$file, $compiledDir.str_replace('.js', '.min.js', $file)); exec($compilerCommand, $return, $code); if ($code != 0) { printf("Fuck! Something went wrong: %s (%s)", join('<br />', $return), $code); } else { printf("%s compiled successfully.", $file); } } } closedir($dh); } }

If you get the error code: (1) or (254) check the permissions of your compiler.jar and "compiled"-directory. Everyone must be allowed to read and execute the compiler.jar and everyone must can write to the compiled folder. 

chmod a+rx compiler.jar