Skip to content

CommonJS Modules and haXe!

May 7, 2010

I’ve just added a small tweak to my haxe fork on github (http://github.com/blackdog66/haxe) which allows haXe  to generate .js files to the CommonJS module standard. Thus, a haXe output JS file can be used by any conforming CommonJS implementation.

The CommonJS standard  is very simple, anything you want to be public must be assigned to the “exports” reference,  you can see some sample code here, http://commonjs.org/specs/modules/1.0/ but basically this

exports.add = function() {
    var sum = 0, i = 0, args = arguments, l = args.length;
    while (i < l) {
        sum += args[i++];
    }
    return sum;
};

There is already a  –js-namespace compiler option that allows the non-packaged haxe classes like Array to be given a package, so a little extension of that idea  and tweak of the Ocaml code generator (in genjs.ml), like this:

if ctx.com.js_namespace = Some "exports" then
print ctx "if(typeof %s=='undefined') var %s = {} ; exports.%s = %s; " p p p p
else
print ctx "if(typeof %s=='undefined') %s = {} ; " p p

allows not just the free classes to be assigned to the namespace “exports” but also all of the other packages. The interesting thing is that all the haXe code is internally consistent as for example,

mypackage = {}

becomes

var  mypackage = {}; exports.mypackage = mypackage

mypackage is still visible as a global within the current source file, and yet there is also an external reference in exports.

I can compile my ChatServer like this this

haxe -cp ... --js-namespace=exports ChatServer

As you can see from the Ocaml snippet the namespace exports is significant, probably a better way to do that but it’s quick and dirty for now.

The compilation provides a ChatServer.js, now I can do the following using Node.js as my platform.

Firing up the node.js command line with node-repl

var cs =require('ChatServer')
new cs.bdog.nodejs.ChatServer('localhost',9000);

this works great. Did you notice haxers, you can use a repl to help test your code?

You can find the Node ChatServer.hx (copy of Ry’s) in my hxNode project.

For the future I’ll be looking to split out the generic haXe stuff into it’s own module and have the other generated modules reference it.

bd

Advertisements

From → haxe, javascript, node.js

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: