12.1.6 Exposing Haxe classes for JavaScript

It is possible to make Haxe classes or static fields available for usage in plain JavaScript. To expose, add the @:expose metadata to the desired class or static fields.

This example exposes the Haxe class MyClass.

@:expose
class MyClass {
  var name:String;
  function new(name:String) {
    this.name = name;
  }
  public function foo() {
    return 'Greetings from $name!';
  }
}

It generates the following JavaScript output:

(function ($hx_exports) { "use strict";
var MyClass = $hx_exports.MyClass = function(name) {
	this.name = name;
};
MyClass.prototype = {
	foo: function() {
		return "Greetings from " + this.name + "!";
	}
};
})(typeof window != "undefined" ? window : exports);

By passing globals (like window or exports) as parameters to our anonymous function in the JavaScript module, it becomes available which allows to expose the Haxe generated module.

In plain JavaScript it is now possible to create an instance of the class and call its public functions.

// JavaScript code
var instance = new MyClass('Mark');
console.log(instance.foo()); // logs a message in the console

The package path of the Haxe class will be completely exposed. To rename the class or define a different package for the exposed class, use @:expose("my.package.MyExternalClass")

Shallow expose

When the code generated by Haxe is part of a larger JavaScript project and wrapped in a large closure it is not always necessary to expose the Haxe types to global variables. Compiling the project using -D shallow-expose allows the types or static fields to be available for the surrounding scope of the generated closure only.

When the code is compiled using -D shallow-expose, the generated output will look like this:

var $hx_exports = $hx_exports || {};
(function () { "use strict";
var MyClass = $hx_exports.MyClass = function(name) {
	this.name = name;
};
MyClass.prototype = {
	foo: function() {
		return "Greetings from " + this.name + "!";
	}
};
})();
var MyClass = $hx_exports.MyClass;

In this pattern, a var statement is used to expose the module; it doesn't write to the window or exports object.