1

I have a javascript-file (lib.js) and I want to use some of the functions in an web page but I don't want to load the full lib.js.

However, I have not figured out how to do what I want. I want to use command line.

lib.js

function dog() {
    return 'Fido';
}

function famous_human() {
    return 'Winston';
}

function human() {
    return famous_human();
}

code-calling-functions-in-lib.js

alert(human());

Desired result, lib-compiled.js

function a() {return 'Winston';}function human() {return a();}
  • Function dog is removed since I don't use it.
  • Function famous_human is is optimized.
  • Function human has its original name since I want to call it from other code.
  • No code from code-calling-functions-in-lib.js

.

java -jar compiler.jar --compilation_level ADVANCED_OPTIMIZATIONS --js lib.js --XXXXXXXX code-calling-functions-in-lib.js --js_output_file lib-compiled.js    

Is there a simple answer to my question?

1 Answer 1

2

You can export human:

function human() {
    return famous_human();
}

window['human'] = human;

More information on exports

Since exporting symbols blocks dead-code elimination, a best practice is to keep the project-specific exports in a separate file and not included in your library.

Example

Library Source - liba.js

function dog() {
  return 'Fido';
}

function famous_human() {
  return 'Winston';
}

function human() {
  return famous_human();
}

Project Specific Exports - project_exports.js

window['human'] = human;

Compile command

java -jar compiler.jar \
  --compilation_level ADVANCED_OPTIMIZATIONS \
  --js liba.js \
  --js project_exports.js \
  --js project_source.js \
  --js_output_file project_compiled.js
7
  • Ok, but can you be more specific? I might be really stupid but I do need an idiot proof example. I have read a lot and tried a lot of examples on this issue but I don't get it to work. Aug 27, 2013 at 17:42
  • Yes @user2473324 As a first try to get it working you can put that line in lib.js. Try it out on closure-compiler.appspot.com/home
    – Paul
    Aug 27, 2013 at 18:19
  • @user2473324 When I compile the three function from your question with that extra export line I get the result: window.human=function(){return"Winston"};, which would allow you to call human() from other scripts, since window is the global context.
    – Paul
    Aug 27, 2013 at 18:20
  • I believe @Chad Killingsworth is more familiar with Closure than me, so perhaps he could give some advice too.
    – Paul
    Aug 27, 2013 at 18:21
  • @user2473324 There is too much to explain in a comment, so I added the example to the answer. Aug 27, 2013 at 18:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.