如何使用谷歌关闭与导出的符号

How to use google closure with exported symbols?

本文关键字:符号 何使用 谷歌      更新时间:2023-09-26

步骤1:我创建一个test.js:

var Helloworld = function()
{
console.log("Hi..");
}
goog.exportSymbol('Helloworld', Helloworld);

步骤2:我使用闭包编译器编译上述javascript文件

java -jar ../compiler.jar --compilation_level ADVANCED_OPTIMIZATIONS --js test.js   --js_output_file test_out.js

我可以看到test_out.js:的内容

goog.a("Helloworld",function(){console.log("Hi..")});'

我不知道"goog.a"是什么意思。

步骤3:我创建一个test.html:

<html>
<head><title>Hello World</title></head>
<body>
<script src="closure-library/closure/goog/base.js"></script>
<script src="test_out.js"></script>
 <script>
    var v = new Helloworld();
  </script>
</body>
</html>

步骤4:在浏览器中加载html。

但是,找不到Helloworld符号。我编译javascript文件的脚本出了什么问题?如果有人能帮忙,我将不胜感激。谷歌关闭的文档和教程不是很简单。

Closure库设计为使用源代码进行编译,以充分利用死代码消除。您缺少的是编译命令中正确的库源文件:

java -jar ../compiler.jar --compilation_level ADVANCED_OPTIMIZATIONS
    --js test.js --js closure-library/base.js
    --js_output_file test_out.js

上述命令将只包括闭包库(包括goog.exportSymbol)的base.js文件中定义的函数。编译时,test_out.js将包含goog.exportSymbol的编译定义。

为了更高级地使用闭包库,您需要正确地使用goog.require调用,并使用闭包生成器来解决依赖关系。

在test.html中,您是否尝试过替换:

<script>
    var v = new Helloworld();
</script>

带有

<script>
    var Helloworld = goog.getObjectByName('Helloworld');
    var v = new Helloworld();
</script>