简体   繁体   中英

Google Closure Compiler - Dead code removal based on externs

I'm trying to use the Google Closure Compiler to split my application code based on where it's going to be run (on the server vs the client) via a single variable. In this example, everything that's going to be called on the server is behind an isServerSide var, BUT, the code is being compiled for the client. So I'll set isServerSide to false and let the compiler remove everything that wouldn't be run by the client...

Inside of 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 of 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 output:

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 to this:

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

Which makes me think I'm setting up my externs.js wrong (or I just don't understand what externs should actually be used for).

Any suggestions on how to get this working?

You specify @define values by setting them in the compiler call directly. Externs serve a different purpose like hyperslug correctly states.

You achieve the expected result by putting the @define definition(from your extern) into app.js and then calling the compiler like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM