Select Page

<– Haxe for JavaScript – Part 1: Introduction

The Haxe toolkit consists of the language, a standard library, and a compiler. Here’s an example that shows how to compile Haxe.

The Haxe compiler is a command line tool predictably named “haxe.” Instead of continually passing options to the compiler on the command line, the convention is to keep options in a .hxml file.

A typical setup might include a directory for haxe source code and directory for compiled javascript:

./
 -- /haxe
 ---- App.hx
 ---- javascript.hxml
 -- /javascripts
 ---- app.js

class App {
private static var private_string: String;
public static var public_int: Int;

// main() is the expected function in the startup class
public static function main(): Void {
private_string = "Compile, dangit!";
public_int = 5;
}
}

Your compiler options hxml file can be named anything you wish. Since this configuration compiles to JavaScript, javascript.hxml seems fitting, right? For now, we only need two options for the compiler.

-main <class> (the startup class in which is defined main())
-js <path> (compile to JavaScript)

-main App 
-js ../javascripts/app.js # 

Now compile from the haxe directory.

haxe javascript.hxml

And behold!

(function (console) { "use strict";
var App = function() { };
App.main = function() {
 App.private_string = "Compile, dangit!";
 App.public_int = 5;
};
App.main();
})(typeof console != "undefined" ? console : {log:function(){}});

Note the following and win:

  • The Haxe compiler expects startup class to be in a file of the same name.  In this example, “-main App” requires that the class named App is defined in App.hx.
  • The startup class must define main() which is the entry point to your application. As many languages do, Haxe treats main() and new() as special functions.
  • Access to private variables is enforced by the compiler even though you do not see that reflected in the compiled JavaScript.

Haxe for JavaScript – Part 3: Classes, Modules, and Packages