Search

11/29/2013

Closure Compiler - Advanced Compilation and Externs

Closure Compiler - Advanced Compilation and Externs - demo: http://chunghe.googlecode.com/git/experiment/closure.compiler/

Inconsistent Property Names Closure Compiler compilation never changes string literals in your code, no matter what compilation level you use. This means that compilation with ADVANCED_OPTIMIZATIONS treats properties differently depending on whether your code accesses them with a string. If you mix string references to a property with dot-syntax references, Closure Compiler renames some of the references to that property but not others. As a result, your code will probably not run correctly.
function displayNoteTitle(note) {
  alert(note['myTitle']);
}
var flowerNote = {};
flowerNote.myTitle = 'Flowers';

alert(flowerNote.myTitle);
displayNoteTitle(flowerNote);
compiles to
var a={};a.a="Flowers";alert(a.a);alert(a.myTitle);
Compiling Two Portions of Code Separately If you split your application into different modules of code, you might want to compile the modules separately. However, if two chunks of code interact at all, you may have trouble compiling them separately. Even if you succeed, the output of the two Closure Compiler runs will not be compatible. Solution: Compile All Code for a Page Together To ensure proper compilation, compile all the code for a page together in a single compilation run. The Closure Compiler can accept multiple JavaScript files and JavaScript strings as input, so you can pass library code and other code together in a single compilation request.
LOCAL_LIB=./lib.js
LOCAL_FILE=./script1.js
OUTPUT=output/script1.advanced.local.min.js  
curl -d compilation_level=ADVANCED_OPTIMIZATIONS -d output_format=text -d output_info=compiled_code --data-urlencode "js_code@${LOCAL_LIB}" --data-urlencode "js_code@${LOCAL_FILE}" http://closure-compiler.appspot.com/compile > $OUTPUT
lib.js
function getData() {
  // In an actual project, this data would be retrieved from the server.
  return {title: 'Flower Care', text: 'Flowers need water.'};
}
script1.js:

var displayElement = document.getElementById('display');
function displayData(parent, data) {
  var textElement = document.createTextNode(data.text);
  parent.appendChild(textElement);
}
displayData(displayElement, getData());
compiled to:
document.getElementById("display").appendChild(document.createTextNode("Flowers need water."));

沒有留言: