Google Closure compiler - removing dead code based on externs

I am trying to use the Google Closure compiler to separate application code based on where it will run (on server and client) with a single variable. In this example, everything that will be called on the server is behind isServerSide var, BUT, the code is compiled for the client. Therefore, I set isServerSide to false and allow the compiler to delete everything that will not be executed by the client ...

Inside app.js :

 goog.provide('my.app'); my.app.log = function(message) { document.write(message); } my.app.initClientSide = function() { my.app.log('hello client'); } my.app.initServerSide = function() { my.app.log('hello server'); } if (isServerSide) { my.app.log('initing server'); my.app.initServerSide() }else my.app.initClientSide(); 

Inside externs.js :

 /** * @define {boolean} is server side? */ var isServerSide=false; 

Command:

 java -jar bin/compiler.jar --js closure-library/closure/goog/base.js --js app.js --externs externs.js --manage_closure_dependencies true --process_closure_primitives true --summary_detail_level 3 --warning_level VERBOSE --compilation_level=ADVANCED_OPTIMIZATIONS --closure_entry_point my.app 

Expected Result:

 document.write("hello client"); 

Actual output:

 isServerSide?(document.write("initing server"),document.write("hello server")):document.write("hello client"); 

If I manually type isServerSide=false; in app.js , then I can get it to compile this:

 isServerSide=false;document.write("hello client"); 

Which makes me think that I'm setting up my externs.js wrong (or I just donโ€™t understand which externs I really need to use).

Any suggestions on how to do this?

+4
source share
1 answer

You specify @define values โ€‹โ€‹by setting them directly in the compiler call. Externs serve for another purpose, for example, for the correct state of the hyperlayer.

You achieve the expected result by putting the @define definition (from your extern) in app.js, and then calling the compiler as follows:

 java -jar compiler.jar \ --define "isServerSide=false" \ --js closure-library/closure/goog/base.js \ --js app.js \ --manage_closure_dependencies true \ --process_closure_primitives true \ --summary_detail_level 3 \ --warning_level VERBOSE \ --compilation_level=ADVANCED_OPTIMIZATIONS \ --closure_entry_point my.app 
+6
source

Source: https://habr.com/ru/post/1380309/


All Articles