How to optimize CasperJS project using Google Closure? - google-closure-compiler

I'm trying to optimize the CasperJS tests run.js code(https://github.com/n1k0/casperjs/blob/master/tests/run.js), so that I could understand how I can use it further to optimize further the tests that I've written. Here's the sample run.js of the CasperJS project that I was trying to optimize using ADVANCED_OPTIMIZATIONS flag to the compiler.
(https://github.com/n1k0/casperjs/blob/master/tests/run.js)
But the optimized code is as below:
phantom.d || (console.log("This script must be invoked using the casperjs executable"), phantom.c(1)); var a = require("fs"), c = require("utils").h, d = require("casper").create({g:!1}); d.options.n = d.a.get("direct") || !1; d.options.i = d.a.get("log-level") || "error"; d.m("open.location", function(b) { return!/^http/.test(b) ? c("file://%s/%s", phantom.e, b) : b }); var e = []; d.a.b.length ? e = d.a.b.filter(function(b) { return a.isFile(b) || a.isDirectory(b) }) : (d.f("No test path passed, exiting.", "RED_BAR", 80), d.c(1)); d.test.j("tests.complete", function() { this.k(true, void 0, d.a.get("xunit") || void 0) }); d.test.l.apply(d.test, e);
Obviously, this is failing as being told by the compiler (Ex: JSC_INEXISTENT_PROPERTY: Property casperLoaded never defined on phantom at line 2 character 5
if (!phantom.casperLoaded) )
Can you please guide me as to how to use the Closure Compiler, to optimize all of the JS files in the project with their dependencies, thus avoiding these errors and proceed further.
I went through the documentation for the Closure, but I wasn't able to figure out the approach needed in this case.
FYI: I was using the Closure compiler.jar

Support has been added to Closure Compiler to make it is easier to work with Common JS and AMD/require.js modules using the following compiler flags:
--transform_amd_modules
--process_common_js_modules
--common_js_entry_module
--common_js_module_path_prefix
See Experimental support for Common JS and AMD/require.js modules in Closure Compiler

Related

Google closure compiler with ADVANCED_OPTIMIZATIONS giving me empty file

Command i am using is
java -jar closure-compiler-v20181028.jar --compilation_level ADVANCED_OPTIMIZATIONS --js_output_file=out.js input.js
my input.js contains only
function base() {
var b='xyz';
if (b.tagName && 0 == b.tagName.search(this.TAGS_)) {
if (b.hasAttribute("href") && void 0 !== self.angular) {
var f = b.getAttribute("href");
if (f.indexOf("{{") >= 0 && f.indexOf("}}") > 0 && !b.hasAttribute("ng-href"))
return b.setAttribute("ng-href", f), void b.removeAttribute("href");
}
for (var a = 0; a < this.URL_ATTRIBUTES_.length; ++a)
if (b.hasAttribute(this.URL_ATTRIBUTES_[a]))
return this.updateAttributes_(b, a);
}
}
i tried with gradle script, also same result .Any help would be appreciated.
From the documentation:
"...code compiled with ADVANCED_OPTIMIZATIONS may not work with uncompiled code unless you take special steps to ensure interoperability. If you do not flag external functions and properties referenced in your code, Closure Compiler will inappropriately rename references in your code, causing mismatches between the names in your code and in the external code."
By "flag" here, they mean "export". For more information see this documentation on the different compilations levels:
https://developers.google.com/closure/compiler/docs/compilation_levels
This blog post:
http://closuretools.blogspot.com/2012/09/which-compilation-level-is-right-for-me.html
And the documentation on exports here:
https://developers.google.com/closure/compiler/docs/api-tutorial3
If you don't call base(), the code will be removed as it is unreachable.
You'll either want to call it or add an #export notation to tell Closure it's needed by other code.
Alternatively, if something is calling base() it may not be properly included in your build.

Cannot identify language in SALT

I just started using SALT for a project i am working on. It is said to work with Python but I find quite a bit of difference in thier syntax and overall format. I have pasted a code for a simple task which just opens and imports and loads some libraries onto the SALT console. I hope someone can check abnd see if he/she can instantly identify the language being used and what the code does. This is because i have a suspicion that the code is a mixture between C, Python as well as Java... if that is so doen't that mean it should be a totally different language on its own?
code:
var rtwxlib = import'rtwxlib';
var string = import'string';
var monitor = rtwxlib.Monitor
{
EvActivate = func() { print "Activate\n"; };
EvShutdown = func() { print "Shutdown\n"; };
EvProgress = func(self, fDone, msg = "") {
print("Progress: %d %s \r"::format(fDone*100, msg));
};
EvEventMsg = func(self, msg) {
print("\nEvent: %s\n"::format(iStat, msg));
};
};
var solver = rtwxlib.Solver(monitor);
solver::Open("test.wrx");
solver::DelGeometry();
solver::SaveAs('testresults.wrx');
solver::Close();
I was able to indentify the syntax of the language used as C. I beieve the problem I had which confused me was the libraries used for this code which I later found out was for a particular program. Thank you to all those who tried to help though :)

SyntaxError: Parse error - Wkhtmltopdf with react-pdf-js lib

I am using wkhtmltopdf version 0.12.2.1 (with patched qt) to render my reactJs app! It worked fine, until I added the react-pdf-js lib to render the pdf generated inside my app. I followed the code described on react-pdf-js documentation (see https://www.npmjs.com/package/react-pdf-js) to make it work.
The pdf is rendered inside my page, and it looks pretty cool indeed. But when I try to run wkhtmltopdf again, to generate a pdf of any page of my app, the following error is returned:
desenv01#desenv01-PC:~$ wkhtmltopdf -O Landscape --print-media-type --debug-javascript http://localhost:3000/report/1 report.pdfLoading pages (1/6)
Warning: undefined:0 ReferenceError: Can't find variable: Float64Array
Warning: http://localhost:3000/assets/js/app.js:46789 SyntaxError: Parse error
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done
Then, I went to my app.js to see what's on line 46789:
set href(href) {
clear.call(this);
parse.call(this, href);
},
get protocol() {
return this._scheme + ':';
},
set protocol(protocol) {
if (this._isInvalid)
return;
parse.call(this, protocol + ':', 'scheme start');
},
The error happens on the line that says parse.call(this, href);, which is part of pdf.combined.js script.
I could not find any solution online so I wondered if there is anyone who might know if I did something wrong or a way to work around it.
Thanks..
I ran into this using wkthmltopdf 12.3 and 12.4 because I have my IDE set to nag me for using var instead of let. The problem is the older Qt engine powering those versions of the program doesn't recognize new-style, ES6 keywords. Not sure if you can down-convert React. Otherwise you can try the bleeding edge versions which use a newer Qt.
I have same problem. I fixed it by modify some code that i think it is new in JS. let keyword (ES5) and template literals (ES6).
generateRandomColor= function () {
let maxVal = 0xFFFFFF; // 16777215
let randomNumber = Math.random() * maxVal;
randomNumber = Math.floor(randomNumber);
randomNumber = randomNumber.toString(16);
let randColor = randomNumber.padStart(6, 0);
return `#${randColor.toUpperCase()}`
}
I modify above code into below
generateRandomColor = function () {
var maxVal = 0xFFFFFF;
var randomNumber = Math.random() * maxVal;
randomNumber = Math.floor(randomNumber);
randomNumber = randomNumber.toString(16);
var randColor = randomNumber.padStart(6, 0);
return "#" + randColor.toUpperCase();
}

Getting errors when Browsery bundle with SquishIt

I am currently refactoring the javascript portions of a web site, and now I have bundled some scripts together using Browserify. The resulting script is bundled along with other resources using SquishIt. In Debug mode, when SquishIt is not bundling all the scripts together everything seems to work just fine, but when running in Production, and SquishIt bundles everything together I get errors from the Browserify part of my bundle. The error is complaining that r has no length property (see line 18) below. This part of the code is created by Browserify when bundling the scripts.
(function e(t, n, r) {
function s(o, u) {
if (!n[o]) {
if (!t[o]) {
var a = typeof require == "function" && require;
if (!u && a) return a(o, !0);
if (i) return i(o, !0);
var f = new Error("Cannot find module '" + o + "'");
throw f.code = "MODULE_NOT_FOUND", f
}
var l = n[o] = {
exports: {}
};
t[o][0].call(l.exports, function(e) {
var n = t[o][1][e];
return s(n ? n : e)
}, l, l.exports, e, t, n, r)
}
return n[o].exports
}
var i = typeof require == "function" && require;
for (var o = 0; o < r.length; o++) s(r[o]);
return s
})({
I really can't think of anything that using SquishIt to bundle all the scripts would break the logic of the browserified scripts. What could be the cause of this? This gist shows the entire source code, in case that is relevant.
I have not changed anything on the ASP.NET side (in the bundling), and the relevant part of my ´Head.ascx´ looks like this:
Bundle.JavaScript()
.Add(Assets.JavaScript.GetUrl("main.js").ToString())
.Add(Assets.JavaScript.GetUrl("Plugins/raphael-min.js").ToString())
.Add(Assets.JavaScript.GetUrl("Plugins/vector_map.js").ToString())
// more ...
.Render("~/Content/"+Assets.VersionString+"/Scripts/Combined/combined.js")
Have a look at this comment it may help https://github.com/jetheredge/SquishIt/issues/320#issuecomment-139921409
Is there a reason you need to use two different bundling solutions?

Using Closure compiler with Underscore.js _.template

Is there any way to compile Underscore.js templates on the server and get the Closure compiler to work with the generated code?
The main problem is that _.template:
_.template = function(str, data) {
var c = _.templateSettings;
var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
'with(obj||{}){__p.push(\'' +
str.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(c.interpolate, function(match, code) {
return "'," + code.replace(/\\'/g, "'") + ",'";
})
.replace(c.evaluate || null, function(match, code) {
return "');" + code.replace(/\\'/g, "'")
.replace(/[\r\n\t]/g, ' ') + "__p.push('";
})
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
+ "');}return __p.join('');";
var func = new Function('obj', tmpl);
return data ? func(data) : func;
};
generates JavaScript with a with-statement in it. The two obvious routes are:
modify Underscore.js's _.template not to generate withs
coerce Closure into playing nice
Is the second option possible?
Generally, the JS engines perform better without "with", so if generating it without "with" is an option that is likely the best solution.
Otherwise your options depend on whether you are hoping to using Closure Compilers ADVANCED mode. In SIMPLE mode, the compiler won't rename your properties on the template, and will assume that any undeclared variable are globals. So as long are your template object isn't causing any local variables to be shadowed it might "just work".

Resources