Search code examples
javascriptgoogle-closure-compiler

How can I tell Google closure compiler to not remove a var


I have the following code:

// ==ClosureCompiler==
// @output_file_name default.js
// @compilation_level ADVANCED_OPTIMIZATIONS
// ==/ClosureCompiler==

var l = window.location;
var s = 'hash';
l[s] = 'whatever i need now';

Which gets compiled with google closure compiler (advanced mode) like this:

window.location.hash="whatever i need now";

But in this case I really need it to keep using l[s]= ... in the compiled code.

Is there a way to tell the compiler to keep using the var or ignore a couple of lines?

Compiler in action - demo


Solution

  • It's a small hack to get the hash function to work properly with junos pulse.

    I'm having a lot of trouble believing the hack is necessary, but:

    // ==ClosureCompiler==
    // @output_file_name default.js
    // @compilation_level ADVANCED_OPTIMIZATIONS
    // ==/ClosureCompiler==
    
    eval(
    "var l = window.location;\n" +
    "var s = 'hash';\n" +
    "l[s] = 'whatever i need now';\n"
    );
    

    *hack* *cough* :-)

    Or:

    // ==ClosureCompiler==
    // @output_file_name default.js
    // @compilation_level ADVANCED_OPTIMIZATIONS
    // ==/ClosureCompiler==
    
    sessionStorage.x = "hash";
    window.location[sessionStorage.x] = 'whatever i need now';