Reputation: 511
I'm adapting some JavaScript code to be transpiled in Google's Closure, using ADVANCED_OPTIMIZATIONS
. I'm using a class
as a namespace:
class MySpiffyClass {
...
}
The class contains methods and static "fields", including many other classes. Everything in the .js file is contained inside this class. Looking forward, there will be ~10 other .js files, each of which contains its own class in a similar manner. HTML documents might use one or several of these files, and I have no control over which ones are used. I don't want any of them to interfere with each other--hence the need for namespaces.
When I transpile, I see no reference to my class MySpiffyClass
in the resulting code. I have to assume that Closure isn't following my wishes. I've tried adding export
to my class definition line, but it didn't seem to have any effect. Any help would be appreciated--I'm new to Closure, and most of the docs don't make any reference to using classes in one's code.
Addendum--here's a minimal version of the file demo.js
:
class MySpiffyClass {
static go() {
window.alert("we're running! " + MySpiffyClass.someValue);
}
}
MySpiffyClass.someValue = 3;
window.addEventListener('load', MySpiffyClass.go, false);
And the HTML file to run it:
<html lang="en">
<head>
<title>Basic Demo</title>
<script src="demo.js"></script>
</head>
<body>
<p>Hello.</p>
</body>
</html>
Upvotes: 0
Views: 211
Reputation: 18901
When I transpile, I see no reference to my class MySpiffyClass in the resulting code.
This sounds like the compiler has mangled all the names which can happen in advanced compilation mode if you didn't provide an externs file.
Here's the smallest reproducible case I can think of:
(cc
is just an alias to invoke my compiler.)
// tmp/repro.js
window.MySpiffyClass = class {}
bash-5.0# cc --compilation_level ADVANCED_OPTIMIZATIONS --language_in ECMASCRIPT_NEXT --js tmp/repro.js
window.g=function(){};
You can see that compiler has mangled the class name.
You can avoid this with an externs file which is a list of symbols that the compiler should not rename:
// tmp/externs.js
var MySpiffyClass;
bash-5.0# cc --compilation_level ADVANCED_OPTIMIZATIONS --language_in ECMASCRIPT_NEXT --js tmp/repro.js --externs tmp/externs.js
window.MySpiffyClass=function(){};
Upvotes: 1