Create a node module with Haxe

In this post, I’m not going to talk about npm (except for the initialisation part), but about how to code your module with Haxe.

Project setup

First thing to do is to create our npm project.

1
npm init --yes

--yes because I’m lazy and I don’t want to enter the default value for each prompt.

My default package.json file looks like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
{
  "name": "test-node-package",
  "version": "1.0.0",
  "description": "",
  "main": "dist/index.js",
  "scripts": {
    "build": "haxe build.hxml",
    "dev": "npm run build -- -debug"
  },
  "keywords": [],
  "author": "RevoluGame",
  "license": "ISC",
  "files": ["dist"]
}

The files parameter will tell npm which file/directory to import while installing the module. I only specify the dist directory, because for a production usage, the Haxe sources are not needed. But still, if you want to publish everything, just forget about the files parameter.

My project looks like:

1
2
3
4
5
6
7
- test-node-package
  - dist
    - index.js
  - src
    - Main.hx
  - package.json
  - build.hxml

The Haxe part

Now that we have our project setup, we can start working on our module.

Let’s say we want to do the following in another project:

1
2
var test = require('test-node-package');
test.foo("world");

In Haxe you will have to:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Main
{
    @:expose("foo")
    public static function foo(bar: String)
    {
        trace('Hello $bar');
    }

    public static function main() {}
}

The @expose metadata will make your method available in Javascript with the name you specified (in our case: foo).

You will probably need to use the nodejs lib, so don’t forget to add it in your build.hxml:

1
-lib hxnodejs