【问题标题】:main() and Closure Compilermain() 和闭包编译器
【发布时间】:2014-07-29 00:10:53
【问题描述】:

我有一些 javascript 在使用 SIMPLE_OPTIMIZATIONS 通过 Closure 编译后运行良好。但我想执行ADVANCED_OPTIMIZATIONS 执行死代码删除。

在阅读了一些相关文档here 之后,我相信我通过<body onload="main()"> 调用的main() 函数正在被我的编译器消除。为了确认这一点,我在main() 函数中添加了console.log('hello'); 代码行。在文本编辑器中打开具有简单和高级优化的 Closure 编译结果时,我可以在简单版本中找到 console.log('hello');,但在高级版本中不存在。

所以我的问题是,有没有一种优雅的方式可以告诉编译器main() 并非不可访问? (或者也许我做错了什么......)

【问题讨论】:

    标签: javascript google-closure-compiler


    【解决方案1】:

    将其与事件侦听器绑定,而不是将其内联到您的 html 中。例如,而不是:

    HTML

    <body onload="main()">Test</body>
    

    JS

    var main = function() { /* Do something */ }
    

    使用

    新的 JS

    var main = function() {
        console.log("Here!");
    }
    window.addEventListener("load", main);
    

    然后您可以从 HTML 中删除 onload="main()"。这也被认为是 JavaScript 中的良好做法。

    【讨论】:

      【解决方案2】:

      您也可以使用--closure_entry_point 标志。无论文件中有main,在该文件中放入goog.provide('myapp.entrypoint') 之类的内容,然后将--closure_entry_point=myapp.entrypoint 传递给编译器。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多