JavaScript intellisense in Visual Studio only partially working - javascript

I'm seeing some strange behaviour with JavaScript intellisense in Visual Studio 2013 Express for Web. I followed all the advice I could google, and it's almost working perfectly.. but something to do with being inside or outside of a function seems to be affecting it. I am very new to JavaScript, so I might be missing something, but this doesn't make any sense to me:
Outside of a function it seems to work partially...
(I get one level of intellisense)
(but not two)
But inside of a function it works perfectly...
(I get all intellisense)
In a separate file, I get a similar problem, but down one function level...
(limited here)
(but everything here)
Any advice would be much appreciated!

OK I've looked through the code here's what I think.
Within Phaser.Game you have this code
/**
* #property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory.
*/
this.add = null;
Because this is initially set to null I'm guessing Visual Studio will not be able to infer what type "add" will be since it is only determined at run time.
If add(...) was defined as Phaser.Game.prototype.add = function() { ... } or even within the function using this.add = function() { ... } I think you would see it in intellisense (this is normally how classes are built in Javascript). However I notice you are defining it dynamically later in the code like this from a factory:
this.add = new Phaser.GameObjectFactory(this);
Visual Studio isn't smart enough to know this is the definition of add(...) it should use for intellisense.
In the second example game is passed as an argument, and visual studio is not smart enough to work out what type this will be. Because Javascript is weakly-typed the argument could be a Game, but could also be an integer, boolean or anything else for that matter.

Related

Dependency tracking modules from a concatenated library

What I've got
A large (proprietary unfortunately) JS library, the many small modules that get rolled up into it during the build process, the accompanying source map, and over 300 examples that use the built version of the library.
The goal
A form of dependency tracking, I guess? I need to be able to modify one of the small modules, rebuild the large file, and then only re-verify the examples that were affected by this change. Note: I don't care whether this requires static analysis or if I have to run all examples thru a headless browser to extract something or so - I'm fine as long as it can be automated.
What I've tried so far
I've read answers to questions like this and tried pre-existing tools like
Madge, but none of them seem to work for my case. Madge in particular is great for telling me which of the modules depend on which modules, but that's not what I'm looking for. Most solutions online are based on the assumption that you're already using something like require.js or similar on which they can piggy-back, but in my case the library is simply just a giant blob.
My current approach is instrumenting the built version of the library by simply appending every line with something like neededModules["the_file_this_line_comes_from.module.js"] = true similar to how code coverage tools do it. However, that fails because of several parts like this:
Points.prototype = Object.assign( Object.create( Info.prototype ), {
plot: ( function () {
var static = new Background();
return function plot( line, physics ) {
<code>
};
}() ),
copy: function () {
return new this.constructor( this.info, this.history ).copy( this );
}
} );
The copy function is tracked/skipped just fine, but because the plot function is an IIFE(right?), the line var static = new Background(); always gets executed, even if there is absolutely no connection to the Points module.
What I'm looking for
Either some help with my current approach and its problems with IIFE or a different solution altogether. I've seen Facebook's Jest does offer dependency tracking, maybe someone has experience with that one, or there's some way to incorporate the source map?
Again, as long as it's automatable and finishes in let's say < 5 min, I'm totally fine with it no matter if it's static analysis or just some hacky script or whatever :)
Thanks!

Chrome console - breakpoint over whole file

is there any option to set something like "breakpoint" on a file in chrome console (kindof shortcut to set breakpoint on every line of code in the file)?
Would be extremely useful when trying to understand 3rd party scripts that you know are executed but have no idea which part of code and from where is executed when.
My current example use case: I downloaded a script (form validation) which does not work as expected. The fastest way to solve the problem would be to pause execution anytime JS runtime enters this file and start exploring it from there.
I think this will be of use to you. I've recently been doing some work on the JavaScript Breakpoint Collection Chrome Extension created by Matt Zeunert, which allows you to inject breakpoints into your code at runtime - including breaking on property access/modifications, functions, scrolling events, etc. You can break on any arbitrary objects as well as the predefined ones using the console API.
Check out the project here.
If you can enumerate the functions publicly exposed by your third party script (for example if they are all properties of an object, or is their name has a pattern) you can make another script which dynamically replaces all those functions and force a break point :
thirdpartfunc = (function () {
var oldfunc = thirdpartfunc;
return function () {
debugger;
oldfunc.call(null, arguments);
}());
With the appropriate binding to this (if any applicable).
If you know the function(s) being called, you can use function breakpoints
debug(function);
function(...args);
When you call the function, it will hit the breakpoint. These aren't saved on page reload, but you can set a line breakpoint once you hit the function breakpoint.
This can get kinda tedious though.
If you have a array of functions, you can do
[function0, function1].map(debug)
#Tibos answer in another post would be good if there was some sort of babel transform to insert debugger; at the start of every function, instead of inserting it manually.
The quickest way for me was to do a global replace of the function declarations in the source, adding "debugger;" at the start.
In other words, replace
function [^{]*{
with
$0 debugger;
Your regexp may vary depending on the escapes you need. For example:
function [^{]*\{
You may also need more than one pattern to handle all the function declarations you have.
This has nothing to do with the Chrome console though.
No. You would have to add breakpoints to the various function entry points that file contains to catch everywhere it could enter.
Can't you just place a breakpoint at the first line of every function in the file of interest?

Strange Javascript validation in dreamweaver CC

I've installed Dreamweaver CC 2015 and found out that I have MYRIAD errors in my working JavaScript files.
Also I have MYRIAD errors in imported JavaScript libraries, including jQuery.
The most important "error" is this one in the beginning of every working function:
Missing "use strict" statement.
It worked quite well without "use strict" and I've never even seen this statement anywhere.
Another strange one is:
Extending prototype of native object: 'Array'.
Here is the code which provokes the warning:
Array.prototype.sortOn = function(key){
this.sort(function(a, b){
if(a[key] < b[key]){
return -1;
}else if(a[key] > b[key]){
return 1;
}
return 0;
});
};
So my options are:
Ditch Dreamweaver and use another IDE (the worst, because it works perfectly fine for my purposes - I'm sole HTML/CSS/JS/PHP/MySQL developer in my project.
Fix all errors like Dreamweaver wants, because it has a good point. Then please explain why? I'm OK with changing "==" to "===", adding "var" before variable declarations, not using "return" after "if" without curly braces, but that "use strict" thing bothers me.
Tweak the JavaScript validation, so only critical errors are shown - the best option for me - but I don't know HOW to do it?
What's the best option to go with?
Any help greatly appreciated.
Here's what I figured out.
The problem was that I was not aware of JSHint and JSLint solutions for validating javascript. JSHint is integrated into Dreamweaver CC and is easily configurable, provided you know what to do.
Normally JSHint has three ways to tweak it, but they don't work in the Dreamweaver environment.
What you should do is:
From the top menu select Edit -> Preferences (Dreamweaver -> Preferences on Mac)
Choose "Linting" from the side menu.
Select "JS" and click "Edit and save changes".
The file JS.jshintrc will be opened in Dreamweaver.
Edit the file like you normally would (see JSHint options) and save.
In my specific case I changed this:
"strict":false,
"undef":false,
"unused":false
...which means that I don't have to put "use strict" everywhere and may leave definitions and usage of variables in different files. YES, I don't use wrapper functions and use lots of globals. YES, I know it's bad, but refactoring this is not the highest priority in my schedule.
Of course I will change all three those options to "true" and refactor all my JS files to comply to standards when the time comes.
Turning off the "undef" check is a sledge hammer, as JSHint will then ignore all variable and function name typos. You won't find the typo until run time, which is annoying and time wasting.
Rather than disabling the "undef" messages completely, I've been using JSHint Inline Directives near the top of my .js files. For example:
/* globals myGlobalVar, myGlobalFunction */
var myLocalVar = myGlobalVar;
myGlobalFunction();
With the globals directive in the file, JSHint will not mark myGlobalVar or myGlobalFunction() as undefined errors. Using "globals" inline directives has the added benefit of documenting the dependencies between your .js files.
Read about JSHint inline directives here:
http://jshint.com/docs/#inline-configuration

Typescript and sql.js - how to tell Typescript it's there

I might be approaching this completely incorrectly, so any advice is appreciated. I'm currently trying to dig in deep to Typescript, and have decided to simultaneously use Sql.js (the JS version of SQLite) at the same time...
My first instinct to use Sql.js was to search for a .d.ts set of bindings around Sql.js so that I could easily start using it with TS. I've come up with no bindings so far (I don't think one exists yet), but figured I could just start "define"-ing in the stuff that I need from the library...
Starting with one of the simple examples from the "sql.js" docs, you have something like this:
var sql = window.SQL;
var db = new sql.Database();
Moving to the typescript side, I wanted to let TS know that after the sql.js library is included, the window object now has a property called SQL, which is essentially the hook to the rest of the library. I figured I needed to do this because, of course, when I type "window." (window-dot) in Visual Studio in my TS file, the Intellisense presented doesn't know about the SQL property now hanging off of "window". So... I dug around Stack, and concluded that I could solve this with a "declare" which I basically see as a way to tell TS just enough about the libraries that I don't have binding files for (.d.ts files).
However, in doing this, I can't seem to construct the syntax for such a declaration. I've tried:
declare var window.SQL : any;
declare var window.SQL;
declare var SQL = window.SQL;
declare window.SQL;
None of these work, of course.
So, the question is, how can I let TS know about new properties introduced by JS libraries on standard objects like "window", and the follow up question is, of course, is this even the right way to be approaching this?
Thanks for any insight.
Now that we have type definitions for SQL.js, and as of Typescript 2.0, the ability to install them easily, you can just do this:
npm install #types/sql.js
Then, that typings file will automatically be picked up by the compiler, and it will know that there is a SQL object. Here is the full definition:
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/sql.js/sql.js.d.ts
window is declared to be of type interface Window (in lib.d.ts). So you need to add to that if you want to use window.SQL :
interface Window{
SQL:any;
}
var sql = window.SQL;
var db = new sql.Database();
Recommend:
Personally I would recommend not using it off of window and just do
declare var SQL:any;
var db = new SQL.Database();
By default the variable access in the browser is on window.
OK, I think I've figured it out, although I'm still not sure if this is the preferred method.
In inspecting lib.d.ts, which is pretty much the heart of the sun as far as declarations go, I found the declaration of the interface for Window more than once. That led me to the conclusion that TS interface declarations (and likely other declarations) can essentially be "partials". It appears that the definition of any interface can be extended by simply adding extra items in a brand new declaration...
So, currently, my angry red squiggly line under "window.SQL" has gone away by simply adding the following:
interface Window {
SQL: any;
}
This seems to work because in lib.d.ts, the "window" variable is defined as a "Window" like this:
declare var window: Window;
... on line 9867 of the file in case others are looking for it. So, the net effect seems to be, I extended the definition of "Window" based on knowing that sql.js would make a new property called "SQL" on it.
HTH, in case anyone else is spelunking the same concepts.

Unminify / Decompress JavaScript

Original Question
This maybe a stupid question but is there a way in VS 2013 to unminify JavaScript?
Just making sure we are all on the same page here.
Minify:
var flashVer=-1;if(navigator.plugins!=null&&navigator.plugins.length>0){if(navigator.plugins["Shockwave Flash 2.0"]||navigator.plugins["Shockwave Flash"]){var swVer2=navigator.plugins["Shockwave Flash 2.0"]?"
That's just an example to make sure we all know what I'm on about. As far as I can tell there is no way to be able to do this. I have only been using VS 2013 for around 3 weeks so there is probably still stuff that is hidden to me.
If there is no way to do this within the program what is the next best thing for this?
I did see on another similar post that recommends the site http://jsbeautifier.org/ , so may have to give that ago but would make life easier if it was built into VS 2013
Thanks in advance as I know someone will be able to help me out here.
Update:
I have looked around VS 2013 and found nothing that can help me with this problem, like I said before they maybe some things I have missed (certain settings) so I guess if it cannot be done in VS what's the next best thing for the job? I seem to run into a fair amount of JS that is minifed and would like the quickest and best way to get the job done. I couple sites I have tried seem to have problems with it, is there a program I could install that would just allow me to short cut it with a hot-key or something. That would be pretty handy.
Update 2:
So I think its safe to say this cannot be done within VS2013, or for that matter at all due to missing var names and so on. So I have seen a few links and programs that allow you to format the code. Is there a way to do with within VS2013? And again if not what is the most reliable website/program that I can use to do this. Like I said I can see there have been answers and I appreciate all of them. I will be leaving this question open for a while to get more people to look at it and possibly give a better answer. Keep it up guys!
Update 3:
If anyone has any more information on this please do share. I am still looking around now and then waiting for someone to come up with something amazing for this. One day people.... One day!
The thing is that you cannot really "unminify" your code since some data was already lost - e.g. variable names. You can reformat it to more readable form though.
According to this question, since VisualStudio 2012 you can just use Ctrl+E, D keyboard shortcut
If the above is not right, there is this extension for VS 2010: http://visualstudiogallery.msdn.microsoft.com/41a0cc2f-eefd-4342-9fa9-3626855ca22a but I am not sure if it works with VS 2013
There is an extension to VisualStudio called ReSharper which can reformat javascript in a few different manners.
Also there are online formatters already mentioned in other answers (if your code is confidential, I would advise some paranoia manifested by downloading sources and using them locally).
Also you may always try to find unminified version of desired library on the interwebs
Also, there is the WebStorm IDE from JetBrains that is able to reformat JS - you may download a trial for the sole purpose of reformatting your minified scripts :)
If that's just to make debugging easier, you may want to use source maps
Also, here is a bunch of related questions:
How to automatically indent source code? <-- this is for VS2010, but it looks promising, maybe it will help you if it supports JavaScript (and it does since VS2012 according to MS support):
Ctrl+E, D - Format whole doc
Ctrl+K, Ctrl+F - Format selection
reindent(reformat) minimized jquery/javascript file in visual studio
Visual Studio 2010 can't format complex JavaScript documents
Visual Studio code formatter
how to make visual studio javascript formatting work?
I am not sure if they figured out a working way to reformat JS, but I've seen a few answers which might be helpful - I am just pasting this in here just FYI.
Added 03.06.2014:
http://www.jsnice.org/
This tool could be useful too, it even tries to infer minified names. As stated on their website:
We will rename variables and parameters to names that we learn from thousands of open source projects.
Personally I can't think of a reason to ever unminify code^:
If you're using a compiled js file (a-la google closure) and want more readable code to debug, use source maps available for well-supported libraries (speaking of jQuery, if it is served from a google CDN it already maps to the correct source)
If you're using a whitespace-only minified js file and want more readable code to debug, you could just toggle pretty print in-browser. This seems to best fit your question.
If you're using either of the above and want to modify the source code for a third-party js file, don't. Any future release will cancel out your change - instead consider one of the many patterns to extend a framework (or, perhaps, do some duck punching depending on the exact scenario.)
The other answers seem to cover the "unminification" process (maxification?) well, but it's worth making sure it's a necessary step first.
^ - Except when version control falls over, there are no backups and the only version of the file left is a minified copy in browser cache. Don't ask.
Its just a one way transformation .... sorry in normal cases you will not get something understandable back from minified JavaScript !
Make just a quick look at JQuery source for a second:
(function( window, undefined ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// The deferred used on DOM ready
readyList,
// A central reference to the root jQuery(document)
rootjQuery,
// Support: IE<10
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "1.10.2",
------
And now at the minify source:
(function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,
l=e.jQuery,u=e.$,c={},p=[],f="1.10.2", ....
I think now you see it =>
window => e
undefined => t
readyList => n
rootjQuery => r
core_strundefined => i
location => o
document => a
So its mapped somehow to make it more shorter look here to minify something
People normally use this so there is no way back
you can just format it look here
If the code has only been minified then the best you can do automatically is reformat to make it more readable. One way of doing this is using an online formatter/beautifier. E.g. Copy and paste the line of code you posted into http://jsbeautifier.org/ or http://www.jspretty.com/ and it'll produce something like this:
var flashVer = -1;
if (navigator.plugins != null && navigator.plugins.length > 0) {
if (navigator.plugins["Shockwave Flash 2.0"]
|| navigator.plugins["Shockwave Flash"]) {
var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? ""
But of course what these don't do is put any comments that have been removed by the minifier back in. And if the code has also been obfuscated then it will be a lot less readable since the variable names will have changed (e.g. var a instead of var flashVer). See here for further details.
As you can see from the other answers, there is no way to reconstitute minified Javascript back into its original form, it is a lossy compression. The best you can do is make it readable by reformatting it.
If the code is open source, then it is likely that the code will exists in a raw state on some form of version control site or as a zip. Why not just download the raw version if available?
There is an online tool to unminify Javascripts
http://jsbeautifier.org/
And also for CSS
http://mrcoles.com/blog/css-unminify/

Categories