Returns element for Javascript vsdocs - javascript

I'm working on fairly heavy client JavaScript application and was looking to add documentation. I went with vsdoc style so as to get picked up by intellisense, but am having trouble defining return objects.
Assuming a function defined as:
function returnObject() {
return { 'prop1': 'value1', method: function(){return 1;}};
}
I'd like to be able to write code as:
returnObject(). and after the . see 'prop1' and 'method' in the intellisense - is this possible without defining an object elsewhere?
How would I define the return object? I've been looking at documentation here, but so far it's been of little help. Looking at the jQuery vsdoc shows me that they almost always return the jQuery object or a simple type. Looking at amplify vsdoc shows that they return Object or undefined and then explain what that object looks like in text.
Can I use the /// element style documentation to define what the return object will look like? Does anyone have any sample of this?

You don't need a vsdoc file for this scenario in visual studio 2012+.
The vsdoc is useful for situations where the internal javascript interpreter can't execute the code, for example web services.
vsdoc files are also useful for when jsdoc style comments are used in the code, and you don't want to have 2 comment formats in the main code files. Jquery is a good example of this.
Also note that vsdoc files are now referred to as intellisense files. However the concept is still the same.
Using inline comments:

Related

How can I use KotlinJS without the stdlib?

Since in most cases we have this:
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version"
}
And the Kotlin standard library seems to large for me.
I want to minimize it by creating my own stdlib, which can be smaller, by declaring only external methods I need.
I tried to remove that method, it compiles, but the generated JS code has this:
if (typeof kotlin === 'undefined') {
throw new Error("Error loading module 'streaking'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'streaking'.");
}
Which means that there must be something necessary in the stdlib, which I don't know.
As my requirements are described above, is there any workarounds?
Or how can I reduce the size of the generated code?
You should make use of Kotlin's kotlin-dce-js Plugin, which does exactly what you want: Minimize the code to what you really use and eliminate the "dead code".
See here:
https://kotlinlang.org/docs/reference/javascript-dce.html#javascript-dce
"There are several ways you get unused declarations: [...] - You are using a shared library which provides much more functions than you actually need. For example, standard library (kotlin.js) contains functions for manipulating lists, arrays, char sequences, adapters for DOM, etc, which together gives about 1.3 mb file. A simple "Hello, world" application only requires console routines, which is only few kilobytes for the entire file."
Here's an alternative. You can kick out the kotlin runtime and make use of this method declaration:
external fun js(code: String): dynamic
Like, if you're using console.log, just write
js("console").log("Hey man")
And remove the check you mentioned in the description. It'll work.

Generate object from Typescript interface

I realize this is essentially the opposite intent of Typescript, but I would like to be able to programmatically generate an object FROM a typescript interface. Basically, I want something like this:
interface Foo {
bar: string
}
const generateObjFromInterface = (Foo) => // { bar: 'string'}
I -do not- mind how contrived the implementation is if it IS possible! If it is categorically impossible that would also be helpful information!
Thanks in advance!
It is possible. As typescript 2.4 is around the corner we can use custom transformers for typescript during compilation and get the list of all properties that are there and as a result create object with such properties.
Here is an example, but please note - as I have said this require to use typescript 2.4+ that is not yet in stable release
Since TypeScript's interfaces are not present in the JavaScript output, runtime reflection over an interface is impossible.
Given this TypeScript:
interface Foo {
bar: string
}
This is the resultant JavaScript:
Since there is no JavaScript, what you want to do is categorically impossible is very contrived.
Edit: Come to think of it, you could find, read, and parse the *.ts source file at runtime.
I also was searching for something that could do it and I didn't find anything. So I build this lib https://www.npmjs.com/package/class-validator-mocker, which can generate random data for classes attributes annotated with class-validator's decorators. Worked pretty well for my purposes.
I did it by using intermock (Google)
Here is a demo page

qx.log.appender Syntax

When declaring qx.log.appender.Native or qx.log.appender.Console, my IDE (PyCharm) complains about the syntax:
// Enable logging in debug variant
if (qx.core.Environment.get("qx.debug"))
{
qx.log.appender.Native;
qx.log.appender.Console;
}
(as documented here)
The warning I get is
Expression statement is not assignment or call
Is this preprocessor magic or a feature of JavaScript syntax I'm not aware yet?
Clarification as my question is ambiguous:
I know that this is perfectly fine JavaScript syntax. From the comments I conclude that here's no magic JS behavior that causes the log appenders to be attached, but rather some preprocessor feature?!
But how does this work? Is it an hardcoded handling or is this syntax available for all classes which follow a specific convention?
The hints how to turn off linter warnings are useful, but I rather wanted to know how this "magic" works
Although what's there by default is legal code, I find it to be somewhat ugly since it's a "useless statement" (result is ignored), aside from the fact that my editor complains about it too. In my code I always change it to something like this:
var appender;
appender = qx.log.appender.Native;
appender = qx.log.appender.Console;
Derrell
The generator reads your code to determine what classes are required by your application, so that it can produce an optimised application with only the minimum classes.
Those two lines are valid Javascript syntax, and exist in order to create a reference to the two classes so that the generator knows to include them - without them, you wouldn't have any logging in your application.
Another way to create the references is to use the #use compiler hint in a class comment, eg:
/**
* #use(qx.log.appender.Native)
* #use(qx.log.appender.Console)
*/
qx.Class.define("mypackage.Application", {
extend: qx.application.Standalone,
members: {
main: function() {
this.base(arguments);
this.debug("Hello world");
}
}
});
This works just as well and there is no unusual syntax - however, in this version your app will always refer to the those log appenders, whereas in the skeleton you are using the references to qx.log.appender.Native/Console were surrounded by if (qx.core.Environment.get("qx.debug")) {...} which means that in the non-debug, ./generate.py build version of your app the log appenders would normally be excluded.
Whether you think this is a good thing or not is up to you - personally, these days I ship all applications with the log appenders enabled and working so that if someone has a problem I can look at the logs (you can write your own appender that sends the logs to the server, or just remote control the user's computer)
EDIT: One other detail is that when a class is created, it can have a defer function that does extra initialisation - in this case, the generator detects qx.log.appender.Console is needed so it makes sure the class is loaded; the class' defer method then adds itself as an appender to the Qooxdoo logging system
This is a valid JS syntax, so most likely it's linter's/preprocessor's warning (looks like something similar to ESLint's no-unused-expressions).
Edit:
For the other part of the question - this syntax most likely uses getters or (rather unlikely as it is a new feature) Proxies. MDN provides simple examples of how this works under the hood.
Btw: there is no such thing as "native" JS preprocessor. There are compilers like Babel or TypeScript's compiler, but they are separate projects, not related to the vanilla JavaScript.

Is there a way to tell Google Closure Compiler to *NOT* inline my local functions?

Here's what I'm looking for:
I want to use the wonderful features of SIMPLE mode minification while disabling just one specific feature (disable local function inline).
UPDATE: The answer is NO, it's not possible given my setup. But for me there is a workaround given I am using Grails.
As #Chad has explained below, "This violates core assumptions of the compiler". See my UPDATE3 below for more info.
IN QUESTION FORM:
I'm using CompilationLevel.SIMPLE_OPTIMIZATIONS which does everything I want, except that it's inlining my local functions.
Is there any way around this? For example, is there a setting I can place in my JS files to tell Google Closure not to inline my local functions?
It would be cool to have some directives at the top of my javascript file such as:
// This is a JS comment...
// google.closure.compiler = [inlineLocalFunctions: false]
I'm developing a Grails app and using the Grails asset-pipeline plugin, which uses Google Closure Compiler (hereafter, Compiler). The plugin supports the different minification levels that Compiler supports via the Grails config grails.assets.minifyOptions. This allows for 'SIMPLE', 'ADVANCED', 'WHITESPACE_ONLY'.
AssetCompiler.groovy (asset-pipeline plugin) calls ClosureCompilerProcessor.process()
That eventually assigns SIMPLE_OPTIMIZATIONS on the CompilerOptions object. And by doing so, CompilerOptions.inlineLocalFunctions = true as a byproduct (this is hard coded behavior in Compiler). If I were to use WHITESPACE_ONLY the result would be inlineLocalFunctions=false.
So by using Asset Pipeline's 'SIMPLE' setting, local functions are being inlined and that is causing me trouble. Example: ExtJS ext-all-debug.js which uses lots of local functions.
SO post Is it possible to make Google Closure compiler *not* inline certain functions? provides some help. I can use its window['dontBlowMeAway'] = dontBlowMeAway trick to keep my functions from inlining. However I have LOTS of functions and I'm not about to manually do this for each one; nor would I want to write a script to do it for me. Creating a JS model and trying to identity local functions doesn't sound safe, fun nor fast.
The previous SO post directs the reader to https://developers.google.com/closure/compiler/docs/api-tutorial3#removal, where the window['bla'] trick is explained, and it works.
Wow thanks for reading this long.
Help? :-)
UPDATE1:
Okay. While spending all the effort in writing this question, I may have a trick that could work. Grails uses Groovy. Groovy makes method call interception easy using its MetaClass API.
I'm going to try intercepting the call to:
com.google.javascript.jscomp.Compiler.compile(
List<T1> externs, List<T2> inputs, CompilerOptions options)
My intercepting method will look like:
options.inlineLocalFunctions=false
// Then delegate call to the real compile() method
It's bed time so I'll have to try this later. Even so, it would be nice to solve this without a hack.
UPDATE2:
The response in a similar post (Is it possible to make Google Closure compiler *not* inline certain functions?) doesn't resolve my problem because of the large quantity of functions I need inlined. I've already explained this point.
Take the ExtJS file I cited above as an example of why the above similar SO post doesn't resolve my problem. Look at the raw code for ext-all-debug.js. Find the byAttribute() function. Then keep looking for the string "byAttribute" and you'll see that it is part of strings that are being defined. I am not familiar with this code, but I'm supposing that these string-based values of byAttribute are later being passed to JS's eval() function for execution. Compiler does not alter these values of byAttribute when it's part of a string. Once function byAttribute is inlined, attempts to call the function is no longer possible.
UPDATE3: I attempted two strategies to resolve this problem and both proved unsuccessful. However, I successfully implemented a workaround. My failed attempts:
Use Groovy method interception (Meta Object Protocol, aka MOP) to intercept com.google.javascript.jscomp.Compiler.compile().
Fork the closure-compiler.jar (make my own custom copy) and modify com.google.javascript.jscomp.applySafeCompilationOptions() by setting options.setInlineFunctions(Reach.NONE); instead of LOCAL.
Method interception doesn't work because Compiler.compile() is a Java class which is invoked by a Groovy class marked as #CompileStatic. That means Groovy's MOP is not used when process() calls Google's Compiler.compile(). Even ClosureCompilerProcessor.translateMinifyOptions() (Groovy code) can't be intercepted because the class is #CompileStatic. The only method that can be intercepted is ClosureCompilerProcessor.process().
Forking Google's closure-compiler.jar was my last ugly resort. But just like #Chad said below, simply inserting options.setInlineFunctions(Reach.NONE) in the right place didn't resurrect my inline JS functions names. I tried toggling other options such as setRemoveDeadCode=false to no avail. I realized what Chad said was right. I would end up flipping settings around and probably destroying how the minification works.
My solution: I pre-compressed ext-all-debug.js with UglifyJS and added them to my project. I could have named the files ext-all-debug.min.js to do it more cleanly but I didn't. Below are the settings I placed in my Grails Config.groovy:
grails.assets.minifyOptions = [
optimizationLevel: 'SIMPLE' // WHITESPACE_ONLY, SIMPLE or ADVANCED
]
grails.assets.minifyOptions.excludes = [
'**ext-all-debug.js',
'**ext-theme-neptune.js'
]
Done. Problem solved.
Keywords: minify, minification, uglify, UglifyJS, UglifyJS2
In this case, you would either need to make a custom build of the compiler or use the Java API.
However - disabling inlining is not enough to make this safe. Renaming and dead code elimination will also cause problems. This violates core assumptions of the compiler. This local function is ONLY referenced from within strings.
This code is only safe for the WHITESPACE_ONLY mode of the compiler.
Use the function constructor
var fnc = new Function("param1", "param2", "alert(param1+param2);");
Closure will leave the String literals alone.
See https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Function

What exactly Javascript prototype is? A library or something builtin Javascript?

I am confused between prototype thing. I have researched and watched tutorials but still I have not been able to get a clear answer. Glad if someone could help me under it. Great if using some simple example or explanation.
Is Prototype a library? e.g. Jquery
If Yes. That means we need to add it to our file before working with it. Like we add Jquery in head and then we get access to it's functions and all.
So we need to learn it before using it because prototype is build using the pure javascript like Jquery is.
If Prototype is a Library then how can we access it without even adding to file ?
For example :- When we are writing some javascript code then we automatically get access to Prototype thing like in this code below.
function Apple (type) {
this.type = type;
this.color = "red";
}
Apple.prototype.getInfo = function() {
return this.color + ' ' + this.type + ' apple';
};
Some people are saying Prototype is actually a Javascript.
If this is right then how we have prototype and jQuery separated in this list from JSFiddle below.
Or is Prototype library like in the image above is different than the Javascript prototype object?
Means these are 2 different things.
Could you please clarify my these 4 points.
Thank you.
It's both.
Javascript has a standard property of objects named prototype, which is used as part of its object-oriented programming mechanism. You can read more about it in this question: How does JavaScript .prototype work?
There's a Javascript framework library called Prototype. You can learn more about it at prototypejs.org
prototype.js is a library that like jQuery makes is easier to register events, select html elements and such.
prototype is also part of standard JavaScript, the code you provided is part of standard JavaScript so you don't need the prototype.js library for that code to work.
Prototype is both a library and standard JavaScript (see answer 1 and 2)
See previous answers
For more info on prototype (standard JS not the library) check this answer.
prototype is a javascript library just like Jquery
you need to include it into your html file

Categories

Resources