Is it possible to make Google Closure compiler *not* inline certain functions?

前端 未结 2 411
悲&欢浪女
悲&欢浪女 2021-02-09 08:05

Closure compiler is inlining a function, but the code size is smaller if that function is not inlined (I only care about code size - this is for JS1k). Can I tell the compiler t

2条回答
  •  既然无缘
    2021-02-09 08:49

    From the tutorial:

    If...you find that Closure Compiler is removing functions you want to keep, there are two ways to prevent this:
    * Move your function calls into the code processed by Closure Compiler.
    * Export the symbols you want to keep.

    You probably want the second, which is discussed here, but basically comes down to explicitly setting it as a window property:

    function foo() {
    }
    window['foo'] = foo;
    

    For your JS1k submission, you'd just leave the last line off as it's unneeded. note that Closure will still rename the function, but as it starts renaming your symbols with the name a and continues from there, it's unlikely to make your names longer overall.

    You can try it out with the online compiler service. If you paste this in:

    // ==ClosureCompiler==
    // @compilation_level ADVANCED_OPTIMIZATIONS
    // @output_file_name default.js
    // ==/ClosureCompiler==
    
    // ADD YOUR CODE HERE
    function hello(name) {
      alert('Hello, ' + name);
    }
    hello('New user');
    

    ...the compiled result is

    alert("Hello, New user");
    

    But if you add

    window['hello'] = hello;
    

    ...to the end, the compiled result is:

    function a(b){alert("Hello, "+b)}a("New user");window.hello=a;
    

提交回复
热议问题