12.2.1 Getting started with Haxe/JavaScript

Haxe can be a powerful tool for developing JavaScript applications. Let's look at our first sample. This is a very basic example showing the toolchain.

Create a new folder and save this class as Main.hx.

import js.Browser;
class Main {
    static function main() {
        var button = Browser.document.createButtonElement();
        button.textContent = "Click me!";
        button.onclick = (event) -> Browser.alert("Haxe is great");

To compile, either run the following from the command line:

haxe --js js/app.js --main Main

Another possibility is to create and run (double-click) a file called compile.hxml. In this example the hxml file should be in the same directory as the example class.

--js js/app.js
--main Main

The output will be js/app.js, which creates and adds a clickable button to the document body.

Run the JavaScript

To display the output in a browser, create an HTML-document called index.html and open it.

<!doctype html>
<html lang="en">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Haxe Application</title>
    <script src="js/app.js"></script>
More information