Use Google Closure Compiler Local with PHP
In “Google Closure Compiler with PHP” i described how you can use the compiler online via http. Now i will show how you do it local on your server with the java command line application …
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 u 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:
-rwxr-xr-x 1 root root 4,1M 17. Jun 01:09 compiler.jar drwxrwxrwx 2 root root 4096 11. Sep 15:12 compiled
Set the right permissions with:
chmod a+rx compiler.jar chmod a+w compiled
And now see it in action on BOHUCO Labs: bohuco.net/labs/google-closure-compiler-php
Tags: closure, closure compiler, compiler, Google, Java, javascript, performance, PHP
