繁体   English   中英

如何使用闭包编译器从另一个压缩文件中获取变量

[英]How to get variable from another compressed file with closure compiler

您好,我想通过Google集成Closure编译器,以ADVANCED_OPTIMIZATIONS模式压缩我的文件,但是我有2个压缩文件,我需要在两者之间共享变量。

我阅读了此文档https://developers.google.com/closure/compiler/docs/api-tutorial3

问题

我收到此错误:

ReferenceError:未定义getValue

所以我试图用window ['getValue']代替getValue,但是它不起作用。

基本代码

第一个JS文件:

var nb0 = 0;
var nb1 = 1;
var nb2 = 2;
var nb3 = 3;

function getValue( nb ) {
    return nb;
}

window['nb0']           = nb0;
window['nb1']           = nb1;
window['nb2']           = nb2;
window['nb3']           = nb3;
window['getValue']      = getValue;

第二个JS文件:

document.addEventListener("DOMContentLoaded", function() { 

    var val = getValue;

    document.querySelector( ".button" ).addEventListener( "click", upButton );

    function upButton() {

        val++;
        document.querySelector( ".show" ).innerText = val;

    }

} );

如果已简短地在链接的文档中的“从编译代码调出到外部代码:外部”的小标题下说明了此问题的解决方案

我想您的困惑来自“第三方”和“外部”这两个词。 在本文档的背景下,你可以假设“第三方”和“外部”指的是代码,其他人写的, 以及来自单独编译的任何文件的任何代码(由您或他人)。

然后,解决方案是在/** @export */添加您不想重命名的var,或者为您的源定义一个externs文件。

备用1

如果您希望以这种方式继续使用window (这可能很难看,恕我直言,有时候这是适当的),则应更改

var val = getValue;

var val = window['getValue'];

例如:

document.addEventListener("DOMContentLoaded", function() { 

    var val = window['getValue'];

    document.querySelector( ".button" ).addEventListener( "click", upButton );

    function upButton() {

        val++;
        document.querySelector( ".show" ).innerText = val;

    }

} );

编译为

document.addEventListener("DOMContentLoaded", function() {
  var a = window.getValue;
  document.querySelector(".button").addEventListener("click", function() {
    a++;
    document.querySelector(".show").innerText = a;
  });
});

备用2

使用ES6模块 Closure Compiler 通过module_resolution标志支持这些module_resolution

一般阅读: 使用模块封装代码

备用3

使用Google Closure库的模块 (goog.module,goog.require和goog.provide(不建议使用))。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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