morisil
morisil

Reputation: 1355

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. I created a small project to highlight the problem. Here is the externs file with public API of my library. I defined it according to:

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:

(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.

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:

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

Upvotes: 0

Views: 169

Answers (1)

John
John

Reputation: 5468

Externs provide definitions for symbols that the compiler should consider to be already existing.

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;

Upvotes: 0

Related Questions