Question

I have simple example:

Javascript:

function testBut(b){
   alert("!");
}

HTML:

<button onclick="testBut(this)">Test</button>

Now I run my .js script through Google Closure compiler (running from commandline), and I want to keep testBut function intact.

I read in many places that I have to use --externs option and define another file with names of exported functions, in this case it would hold just:

function testBut(b){}

And additionally I need to add funny line to my js code:

window['testBut']=testBut;

So now questions:

  • is that really so stupid system in Closure with two bug-prone steps to be done, in order to keep desired function?

  • is there no "@..." annotation that would simply suit same purpose? I tried @export, but it requires --generate_exports option, and still it generates similar ugly and useless goog.a("testBut", testBut); in target code (I tried same code, and those goog.a(...) seems simply useless), and this still requires the exports file

Ideally I'm looking for simple annotation or commandline switch that would tell "don't remove/rename this function", as simple as possible, no code added, no another file.

Thanks

Was it helpful?

Solution

Don't confuse externs and exports.

Externs - provide type information and symbol names when using other code that will NOT be compiled along with your source.

Exports - Make your symbols, properties or functions available to OTHER code that will not be compiled.

So in your simple example, you need:

function testBut(b){
   alert("!");
}
window["testBut"] = testBut;

However this can be simplified even further IF testBut is only for external calls:

window["testBut"] = function(b) {
  alert("!");
};

Why not always use the second notation? Because internal usage (calls within the compiled code) would then have to use the full quoted syntax which blocks type checking and reduces compression.

Why not use a JSDoc Annotation for Exports?

This question comes up a lot.

For one, there isn't global consensus on how exports should be done. There are different ways to accomplish an export.

Also, exporting symbols and functions by definition blocks dead-code elimination. Take the case of a library author. The author wishes to compile his library exporting all public symbols. However, doing so means that when other users include his library in a compilation, no dead-code elimination occurs. This negates one of the primary advantages of ADVANCED_OPTIMIZATIONS.

Library authors are encouraged to provide their exports at the bottom of the file or in a separate file so that they can be excluded by other users.

It has been suggested before to provide a command line argument to control exporting based on a namespace. IE something like --export mynamespace.*. However, no author has yet tackled that issue and it is not a trivial change.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top