首页 > 解决方案 > 闭包编译器不编译 ES6 库

问题描述

我正在使用 Closure Compiler 编写一个相当大的 JavaScript 库,但我制作了一个较小的模型以用作此问题的示例:

src/main.js

export function main(str) {
    console.log("From main: " + str);
}

命令:

google-closure-compiler --compilation_level ADVANCED_OPTIMIZATIONS --language_in ECMASCRIPT6 --language_out ECMASCRIPT6 --js_module_root src/ --module_resolution node --js src/main.js --js_output_file build/main.min.js

预期结果(大致):

export function main(str){console.log("From main: "+str)}

实际结果:

'use strict';

长话短说,我已经挣扎了好几个小时,我不知道如何让 Closure Compiler 尊重 ES6“导出”语句。我已经尝试过多次谷歌搜索,但我只能得到"goog.modules"的结果,这不是我想要的。任何帮助,将不胜感激。

标签: javascriptgoogle-closure-compiler

解决方案


如果你只用 ADVANCED_OPTIMIZATIONS 编译下面的函数,Closure Compiler 会产生空输出:

函数 displayNoteTitle(note) { alert(note['myTitle']); }

因为在传递给编译器的 JavaScript 中永远不会调用该函数,所以 Closure Compiler 假定不需要此代码!

参考

您应该添加一个调用您的函数的部分

function displayNoteTitle(note) {
  alert(note['myTitle']);
}
displayNoteTitle({'myTitle': 'Flowers'});

或者您可以将其添加到窗口对象

function displayNoteTitle(note) {
  alert(note['myTitle']);
}
// Store the function in a global property referenced by a string:
window['displayNoteTitle'] = displayNoteTitle;

活生生的例子


推荐阅读