Ok this one is tricky, I have been stucked for a while...
Way you do this with grunt-contrib-uglify for frontend JS
create multiple files like
SomeClass.js
OtherClass.js
main.js
and use some module (grunt-file-dependencies or grunt-contrib-concat) and setup it to concat your files. Then setup uglify in your Gruntfile.js
like
...
uglify: {
options: {
wrap: "myPublicObject",
...
},
In file (main.js
for example) exports
variable has to be assigned, the entire file might look like this:
var otherClassInst = new OtherClass();
var someClassInst = new SomeClass();
exports = otherClassInst;
Now what it exactly does
Uglify will pick superior context (this
) and define property on it named myPublicObject
. Then it wrap your sourcecode with function and create exports variable here (DO NOT DECLARE var exports
anywhere). At the end it will assign what you exported to that property. If you dont assign anything (you dont use exports =) inital value is {}
, so the property with void object exists anyway.
To make this super-clear,
- if you put your code into page like
<script src="myminifiedfile.min.js"></script>
, then superior context is window
=>
window.myPublicObject
is instance of OtherClass
while window.someClassInst
, window.SomeClass
and window.OtherClass
are undefined
.
- this is unlikely, but if you just copy content of minified result and wrap it with different function, object you exported will be visible only via
this["myPublicObject"]
=> uglify wrap doesn't make things globaly accessible, it makes them accessible in superior context.