HaxeDoc2

(やまだぃちぅ) #1

Chapter 12


Target Details


12.1 Javascript...........................................


12.1.1 Loading extern classes using ”require” function


Since Haxe 3.2.0

Modern JavaScript platforms, such as Node.js provide a way of loading objects from external
modules using the ”require” function. Haxe supports automatic generation of ”require” state-
ments forexternclasses.
This feature can be enabled by specifying@:jsRequiremetadata for the extern class. If
ourexternclass represents a whole module, we pass a single argument to the@:jsRequire
metadata specifying the name of the module to load:

1 @:jsRequire("fs")
2 extern class FS {
3 static function readFileSync(path:String,
4 encoding:String):String;
5 }


In case ourexternclass represents an object within a module, second@:jsRequireargu-
ment specifies an object to load from a module:

1 @:jsRequire("http", "Server")
2 extern class HTTPServer {
3 function new();
4 }


The second argument is a dotted-path, so we can load sub-objects in any hierarchy.
If we need to load custom JavaScript objects in runtime, ajs.Lib.requirefunction can be
used. It takesStringas its only argument and returnsDynamic, so it is advised to be assigned
to a strictly typed variable.
Free download pdf