如何使用Closure Compiler优化Javascript并保留函数名称?

时间:2013-08-27 15:06:02

标签: javascript google-closure-compiler

我有一个javascript文件(lib.js),我想使用一些 在网页中的功能,但我不想加载完整的lib.js.

然而,我还没弄明白如何做我想做的事。我想要 使用命令行。

lib.js

function dog() {
    return 'Fido';
}

function famous_human() {
    return 'Winston';
}

function human() {
    return famous_human();
}

代码调用函数合lib.js

alert(human());

期望的结果,lib-compiled.js

function a() {return 'Winston';}function human() {return a();}
  • 由于我不使用它,因此删除了功能狗。
  • 功能famous_human已经过优化。
  • 函数human有其原始名称,因为我想从其他代码中调用它。
  • 没有来自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    

我的问题有一个简单的答案吗?

1 个答案:

答案 0 :(得分:2)

您可以导出人类:

function human() {
    return famous_human();
}

window['human'] = human;

More information on exports

由于导出符号会阻止死代码消除,因此最佳做法是将项目特定的导出保存在单独的文件中,而不包含在库中。

实施例

图书馆资源 - liba.js

function dog() {
  return 'Fido';
}

function famous_human() {
  return 'Winston';
}

function human() {
  return famous_human();
}

项目特定出口 - project_exports.js

window['human'] = human;

编译命令

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
相关问题