Alexandr Krivosheev Alexandr Krivosheev - 1 month ago 17
Dart Question

how is dart compiled into javascript?

I compile my .dart file with dart2js, but compiled .js file contain code that I did not expect to see. How does dart compiles into javascript?

dart code:

import 'dart:html';


void main() {
querySelector("#answer").onClick.listen(check);
}

void check(MouseEvent event){
var answer;
answer = (querySelector("#text_answer") as InputElement).value;
answer = answer.toUpperCase();

if (answer == "CHOCOLATE") {
querySelector("#text").text = "Smells like... you are right! Well, try to find somthing round, made of glass;)";
return;
} else {
querySelector("#text").text = "No, No, No. Try one more time. There’s white and milk and dark. These three types you might eat. As a type of candy, it really can’t be beat";
}
}


compiled .js code has more than 7000 lines(without comments).

Answer

There is quite a bit of code included that emulates features Dart provides, but that can't be translated directly to ES5, (like classes, mixins, ...).

There is also quite some code included that polyfills missing browser features to make the same Dart code work in all browsers like for example jQuery does.

This code could theoretically be put in a library file (like jQuery) but that file would be huge.

To reduce the size Dart uses tree-shaking (actually it's tree-growing to get rid of all code that is not actually referenced from the main() file (direct or transitive). Also all methods of classes that are not used or functions of libraries that are not used of classes and libraries where other parts are used, can be removed.

This means that for every application the parts of the Dart base library that are actually included in the JS output can and probably will differ. Therefore there can't be a default dart.js file to add to index.html in addition to the JS generated from your hand-written application code.

Comments