Show HN: C#-to-JavaScript compiler powered by Microsoft Roslyn
duoco.de
duoco.de
I've seen projects use a compiler similar to this, and while writing C# sounds great to developers who already know C#, the differences between the C# source and the generated JS make debugging and maintenance difficult.
In my experience typescript provides C# developers much of what they are looking for - type safety, familiar class definitions, etc - while still being very easy to debug.
Like many others I think the future of JavaScript is going to be treating it like bytecode. Write your application in whatever language you want for developer convenience and debugging, them push it out to javascript for processing. Seems to be where things are headed.
My "Show HN" submission yesterday[0], the web app for helping homeless youth find beds and shelter[1], is written in TypeScript.
[0]: https://news.ycombinator.com/item?id=8886588
[1]: http://ysnmn.org
Isn't this solved with source maps?
> DuoCode automatically generates source mappings
Also TypeScript is supported by IntelliJ family of IDEs.
But if you're looking to write C# in the browser because you love C# and have heard JS is terrible (a BIG factor I've seen used when pushing tools like this), I'd look at typescript first.
The biggest part of these projects is the re-implementation of the .NET CLR in JavaScript (for example, Saltarelle began life using the Script# runtime with a few tweaks). The more production usage the runtime has seen, the more useful the translation tool becomes!
// JavaScript code generated by DuoCode
GetBestMove = function(board, player, winner)
That line will garbage the global scope..(Consider: the C# code has no main function, so, if we hid the GetBestMove definition from the rest of the webpage, it would never get called. The optimal Javascript compilation would be an empty string, and that's clearly not valuable.)
var AI = {
GetBestMove: function(....) { ... },
...
};
?Another thing, I had someone tell me once that according to Erik Meijer (of LINQ and Rx fame), years ago, Microsoft tried a C#-to-JS compiler too. It worked, but they had good reasons to drop the project anyway. Did you ever hear about that, do you know Microsoft's reasons for doing TypeScript instead? Are they still valid?
- Scala / Scala.js (http://www.scala-js.org/) and I'm actually using this one for a non-trivial app
- Clojure / ClojureScript (https://github.com/clojure/clojurescript) with some companies using it in production
Both are using Google's Closure compiler to do tree shaking minification and are emitting source maps for the compiled code, so the size of the compiled artifacts is manageable in spite of the huge standard libraries they come with and debugging works well. Normally if you want tree shaking with Google Closure, you have to write code specific for Google Closure, however these compilers are doing that for you.
What you get in comparison with Javascript are saner languages that aren't just a prettified Javascript - completely different type system, awesome standard libraries, packages, saner semantics overall; you get a sane dependency management and build process, by means of their build tools (SBT and Leiningen respectively); you get libraries that are cross-compiled for the JVM and Javascript, so you can do code sharing between the server and the browser and you can use mostly the same tools, like IDEs. For example it's a great experience to use IntelliJ IDEA for targeting the browser with Scala - you get code completion, refactoring, the works.
And yes, the compiled size of the final artifact is a source of worry, but in practice I found to not be an issue and what's awesome is that in the long run it actually saves bandwidth for heavy apps. With Javascript many people tend to avoid using third-party libraries, because every imported library adds to the download size, however with tree shaking you're paying only for what you use. As I mentioned, being a Scala developer I picked up Scala.js and it's completely awesome, in spite of the project being young. Unfortunately these heavier alternatives to Javascript haven't picked up popularity - for some reason people preferred putting lipstick on Javascript and pretend that it's a new language.
I'm happy that compilers for C# are happening as well. My only gripe is that in true .NET fashion I'm not seeing a link to the source, which makes me think that this won't be open-source. Which is a pity.
With es6 around the corner and the possibilities those features will provide, i would still bet on pure js. Those precompilers will benefit a great deal too. Symbols and Proxies alone will remove a lot of the hoops they have to go through now.
I don't get this argument on the size of a hello world, given that JQuery 1.11 is over 270 KB and most people are just doing simple DOM selection with it, yet they don't complain their hello world comes with 270 KB of stuff they'll never use. Factor in React, Bootstrap, Angular.js or what have you and you can easily reach 1 MB of stuff that's never used for a couple of lines of code.
The app doesn't explode in MB, unless those MB are really needed - which is the fundamental difference between how these work and regular Javascript development. And given that there are some companies using these in production for non-trivial stuff and that nobody has ever reported that, I'm thinking that it doesn't happen.
My current app is currently clocking at 300 KB btw, but I am using the collections from the standard library, I am using a library for reactive streams built by myself, I am using React and I do have some code in it. And personally I find it OK.
https://github.com/jashkenas/coffeescript/wiki/list-of-langu...
Supporting reflection might make it difficult to reduce the compile size of the javascript code in the future.
Or does c# reflection work differently from java?
Looks great by the way.
The native compilation technology is moving over to normal .Net and I would imagine the runtime definition file could be used for javascript transpiling tree-shaking as well.
https://github.com/WeTheInternet/xapi/tree/master/gwt/gwt-re...
If you want to support complete reflection across the board it greatly swells compile size, but I have made it so you can be selective about what supports reflection, in order to avoid code bloat.
How much do the threads actually work yet? How slow are they?
I'm not sure how the other transpilers expose native javascript, but in the future of Gwt, interacting with plain javascript is dead simple; you get the best of both worlds; typed java code, and low-level js performance. The JsInterop stuff makes wrapping native js super easy, just define an interface that matches the JS, and it "just works" (tm). Even web components, just create an annotated interface, define default methods, and the compiler attaches them to custom element definitions. I could go on and on, but I'll save it for the correct forum (i.e., the gwt.create conference). :D
Real threading would have to use ES6 yield/generators to translate an entire thread into a spawn loop so that async/await blocks can be emulated.
* Runs on the client and on the server
* async/await
* Well designed stdlib
* Powerful intellisense support
* Stream and Future based APIsAlso, if there any language left that doesn't convert to JS?
Edit: After reading more, this does not seem to be a Microsoft project.
"DuoCode is an alternative compiler, powered by Microsoft® Roslyn, and integrated in Visual Studio."
References this company: www.eternix.co.il
Please stop these C# to JavaScript compilers. If one needs to program in JavaScript, let them learn and understand JavaScript.
All the cool kids will finally stop trying to push everything to the browser, move some of that back to the server, and become completely content with what Javascript has to offer.
Smart clients reduce server load, and allow increased scale; why pay to make your server turn models into HTML when you can just send the model to the client and let it deal with it however it wishes.
For us at Appian, we use the same models and APIs for web, android and IOS; by having a smart client, the server only has to care about the shared model and executing requested instructions; it doesn't care how the client renders the result, nor should it.
obj.Function(() => { ... }); Func<string> blah = () => "im a function";
JavaScript: var blah = function(){ return "im a function"};
Not only is it not harder, it's more terse in C#.var blah = () => "im a function";
Func<string> blah = () => "im a function";
var blah = new Func<string>(() => "im a function");But you can have a generic extension method that returns one of the types and then via inference you can do it implicitly typed.
It shoud be something like this in C# 5:
public static class Lamb
{
public static Func<T> da(this Func<T> f)
{
return f;
}
}
and then: var egocentricFn = Lamb.da(() => "im a function");
I find it really useful not for Func's but for Expressions, as the type declarations can get pretty long.string blah() => "im a function";
Ceylon:
String blah() => "im a function";
Coincidence? Just kidding.
The fact that, for instance, you can use ES6 modules, and it will be converted to whichever module loading system you're actually using (AMD or Browserify, for instance), means that our code is actually more portable now (our React/Flux/browseify app may well have to be integrated into a project that uses backbone/AMD soon, so that's no longer a headache.
JavaScript:
var blah = function(){ return "im a function"};
C# 3.0: var blah = delegate { return "im a function"; };
C# 2.0: Func<string> blah = delegate { return "im a function"; };Every language works pretty well for solo personal projects. It's when you scale up to dozens of team members and millions of lines of code that some things don't work as well.
Other benefits include not having to remember the 'interesting' rules around 'this' in pure JS (though that occassionally slips through in libraries that use it). Having saner (to my eyes) syntax for modules and encapsulation. And having intellisense support in Visual Studio reduces the effort of writing the code.
With a strong typesystem I can first figure out what I need to do, then write it (like a fews of hundreds of lines), compile it and be fairly confident that the program runs almost correctly. Static typesystem does not help with the bugs that have to do with bugs in algorithms (wrong iteration order etc.) but it let's me concentrate on those parts mostly.
Static typing also functions as a self documentation - I see the intended program flow from the type signatures and do not need other means necessarily to figure out what the program flow is.
To me types are like lego bricks and dynamic languages are like ducktape - both have their uses.
I love it when I can get the computer to hold my hand and limit my actions. Personally I feel the limits of my cognition and enjoy when the computer assists in proofing the correctness of my programs.
That way I can be more sure I don't do anything that breaks the program logic and that developers that come after me remain within the boundaries of correctness when modifying my code. Types don't help in design but they help in forming a coherent whole.
I've figured out there are two constraint systems I can use to effectively write correct programs. One of them is a typesystem and the second is set theory.
Granted, the most mainstream statically typed languages come with so much syntactical baggage and lack type hinting (C++, Java, C#) that they can effectively hide the elegance of types as a problem modeling tool.
Types can be used just as a non-value adding anal-retentive bureaucratic baggage but that's not how they should be used.
I'm professionally mostly a C++ programmer but did not really 'get it' until I familiarized myself with functional languages (Ocaml, F#) which helped me understand how to actually leverage a typesystem to help me write correct code instead of 'just using typedeclarations because the compiler is too stupid to figure out what I want to do'. To be precise, the languages themselves did not really teach me that much but the learning materials I used with those language did.
When I need to do something small data processing in a jiffy I usually pick Python. For small programs few-liners in dynamic languages are usually a win.
What do you mean with set theory? I'm asking because languages like Ceylon and Whiley have union and intersection types which are basicially set theory.
What I mean that I first model a particular problem on pen and paper as a group of set operations and identities and then implement that using container operations. I.e. a set as a container, or a particular subset of the elements in the container. I totally depends on the program whether that simplifies things or not.
But for instance, I usually find that rather than adding lots of state variables to entities I model state as those objects belonging to various sets. I.e. store object Id in a list pertaining to a particular property.
This way subsystems can be implemented in a non-invasive, and extensible way. The set operators (union, difference etc.) do not need to be implemented explicitly, rather just figure out what is the most simple isomorphic routine to compute the output for that particular operation.
Refactoring and maintaining consistency are the two big problems we have with Javascript. It's easy enough to write javascript that works and does what we need it to do. The challenges come in when you start having separate components that need to interoperate.
eshint/jshint etc take you only so far (preventing you from dumping things into the global scope, avoiding typos). AMD etc can take you a bit further with async loading, and give a better [more consistent] pattern for exporting things than saying to devs "just put your stuff in an IIFE". FB Flow looks helpful, but it's trying to solve a difficult problem, and unfortunately doesn't work so well with our code thanks to ONE bad decision made a long time ago to rely on declaration hoisting ("unreachable code" :( ).
Anyways, knowing that your code isn't going to work before you start spinning up the application saves a lot of time.
Knowing that you can rename a method/function and have no undefined errors come out of it is great. Being able to look up usages of a method across the entire codebase is also useful. Eventually if Microsoft decide to spend resources on it, TypeScript might get CodeLens (which is on its own all manner of cool+useful).
Having class syntax means that you don't need to worry about external consumers accessing properties that they shouldn't be (+gets rid of silly conventions like underscore private members/methods).
JS is a great language, and it's powerful, but when you're writing large quantities of stuff, sometimes you need structure. Particularly when it's a large team and there are people of wildly varying experience, ranging from near-zero JS experience to people who have used it for a decade or more.
Browserify can help with breaking your code down into smaller reusable modules for the client side and node you want to make your modules as small as possible? From the sounds of it you fell into the one big huge application that does everything problem instead of breaking it up. The same issues would have happen if you would have done that in any other language.
Varying experience doesn't mean you can give them TypeScript or CoffeeScript and not mess something up. You should still put code reviews and training in place though I do agree JavaScript lets you shoot yourself in the foot much easier.
You can hide variables through closures and sorry not a fan of getters and setters, I feel they are a anti-pattern (http://www.yegor256.com/2014/09/16/getters-and-setters-are-e...).
The one thing that would be nice would be knowing where your code is called. Though if you are using NPM and Browserify then that can be easier as well. I agree though that the tools are not as nice as Visual Studios find callers and the intellisense isn't that good ether but I am willing to trade them for the flexibility of not having to declare types and the simplicity of not having to work around types with generics, interfaces, and casting.
So I think there is structure in Javascript you just have to learn the best ways of implementing it. Yes Javascript makes it a little easier to shoot yourself in the foot but you can still do it with CoffeeScript, TypeScript, or even in C# and Java, we learn from our mistakes. I fell to be successful in Javascript you really need to keep it small and re-factor often but that really is the same in all languages.
We have unit tests (fewer on the client than server though), CI that runs integration tests, automated UI tests and other stuff - but that's all much slower than "VS tells me that my code's broken so I should fix it before starting to debug". We'll catch bugs with TS or JS, it's just how long it takes to catch them that's the issue.
Modules aren't so much an issue for us (we don't have a big ball of mud IMO), it's how these modules talk to one another. This is not a problem that we experience in our serverside code because we have powerful tools (in terms of the IDE) that largely stop us from doing dumb things. We refactor a lot, and historically doing this in js has been a massive pain (ie there are no GOOD automated tools for refactoring that I'm aware of). If you use C# and move a method, you expect everything to keep working, but you don't have that same expectation when refactoring javascript. If your app is structured correctly, you do get that with TypeScript.
Same with reviews and training - we have both, but our team isn't big enough to have people dedicated to each area. We mostly hire C# devs, for better or worse, and want them to be as productive per hour as possible. Having it harder to shoot yourself in the foot means fewer feet shot over time, regardless of the team and their skillset.
Getters/setters was an unclear use of term "properties" on my behalf (which actually referred mostly exclusively to methods). Regardless of my personal opinions on getter/setter methods/closures etc, we have established patterns that will take a while to change. The problem is there, and so tooling that helps reduce what breaks when we make changes is a big plus. We don't have a robust message bus in the application, so there's a lot of crosstalk (that's a refactoring area).
And, overall, TS is a superset of javascript so you can always just write JS if that's what you've gotta do.
I guess that my overall point is that javascript is a great language (well, it's ok), but that tools like TypeScript just make things "better" for the average developer working on a large-scale system. JS is an organically grown language, and it shows in a number of places. You can do some super-cool things with it, sure, but for a lot of uses it's a worthwhile tradeoff to write something in a slightly-more-strongly-typed way.
We're about 10% new code, 90% refactoring and updating (though that's a guess, I haven't looked at the stats lately). For us, JS is more painful to maintain than C#. From what we've seen, TypeScript will give us significant benefits on that 90%.