Import Haxe modules into a node.js script

不打扰是莪最后的温柔 提交于 2019-12-04 10:03:56

Consider this

//Haxenode.hx

class Haxenode {
  @:expose("hello")
  public static function hello(){
    return "hello";
  }
}

@:expose("hello") part is to put something in module.exports.

Now launch

haxe -js haxenode.js -dce no Haxenode

Now you can use haxenode.js in nodejs

var haxenode = require('./haxenode.js');
var hello = haxenode.hello;

So, this combined together is an answer to your question:

var cp = require('child_process');

function requireHaxe(haxeClassPath,cb){
    //generate a JavaScript module from the Haxe file, and then return the generated JavaScript module

    cp.exec('haxe -js haxenode.js -dce no ' + haxeClassPath,function(err){
        if (err){
            cb(err); return;
        }

        cb(null,require('./haxenode.js'));
    });
}

Mind that output filename is a stub.

But don't do that - better to compile haxe as build step (with all necessary compile options) and then use regular require at runtime.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!