简体   繁体   English

Closure Compiler - JavaScript 库项目的最佳实践?

[英]Closure Compiler - best practice for JavaScript library projects?

I am trying to use Closure Compiler to minimize and validate my JavaScript library and I am struggling with one issue.我正在尝试使用 Closure Compiler 来最小化和验证我的 JavaScript 库,但我正在努力解决一个问题。 I created a small project to highlight the problem.我创建了一个小项目来突出这个问题。 Here is the externs file with public API of my library.这是我图书馆的公共 API 的外部文件。 I defined it according to:我根据以下定义:

https://developers.google.com/closure/compiler/docs/externs-and-exports https://developers.google.com/closure/compiler/docs/externs-and-exports

/**
 * @fileoverview Public API of my-lib.js
 *
 * @externs
 */
const myLib = {};

myLib.foo = function() {};

And here is the implementation:这是实现:

// const myLib = {};

myLib.foo = function() {
  console.log("foo");
};

So the problem is that if I uncomment the first line, I am getting this error:所以问题是,如果我取消注释第一行,我会得到这个错误:

my-lib.js:1:6: ERROR - [JSC_REDECLARED_VARIABLE_ERROR] Illegal redeclared variable: myLib
  1| const myLib = {};
           ^^^^^^^^^^

If I don't, the output looks like this:如果我不这样做,output 看起来像这样:

(function(){myLib.foo=function(){console.log("foo")};})()

Which is good, because myLib.foo didn't get renamed so the externs are working, but in the same time the myLib namespace has not been created.这很好,因为myLib.foo没有重命名,所以 externs 可以工作,但同时myLib命名空间还没有创建。

What would be the best practice for solving such an issue, or if there is none, maybe there is some workaround instead?解决此类问题的最佳做法是什么,或者如果没有,也许有一些解决方法?

I pushed this example to github:我把这个例子推送到 github:

https://github.com/morisil/closure-compiler-lib-example https://github.com/morisil/closure-compiler-lib-example

Externs provide definitions for symbols that the compiler should consider to be already existing. Externs 为编译器应该认为已经存在的符号提供定义。

There are a couple of solutions:有几个解决方案:

/** @suppress {const,duplicate} */
const myLib = {}

or use a separate name internally and assign it in a way the compiler won't check:或者在内部使用单独的名称并以编译器不会检查的方式分配它:

globalThis['myLib'] = myInternalName;

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

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