COMMUNITY

Javascript modules

Hej all !

Is there a way to import an extern (from cdn i.e.) js lib on runtime that uses modules just in raw haxe js without any lib please ?
Or just use import { foo } from './bar.js' ?

You know because Typescript ES6 webpack, UMD, ESM, CJS, node npm, npx, browserify -esmify, bundle, commonJS, require, AMD, Bower, Yarn… :upside_down_face: :parrot: :confounded: :rofl:

perhaps like this?

var script = document.createScriptElement();
script.async = true;
script.defer = true;
script.onload = function () script.parentNode.removeChild(script);
script.onerror = function (e) trace('Failed to load script $script', e);
script.src = src;
document.head.appendChild(script);

Thanks for your answer @serejek but I think my question was not clear. I want to do an import like import { foo } from './bar.js' and use foo in haxe code.

We really need this feature in Haxe. There’s currently a growing trend in the NPM ecosystem to completely abandon CommonJS modules in favor of ES modules.

@filt3rek Not convenient at all: you could eventually use a dynamic import. Something like:

// Let's say that the "./bar.js" module exports a string named "foo".
typedef BarModule {
  var foo: String;
}

final promise: js.lib.Promise<BarModule> = js.Syntax.code("import({0})", "./bar.js");
promise.then(barModule -> trace(barModule.foo));
1 Like

Or:

// imports.js
import { foo } from './bar.js'

// Main.hx
function main() trace(untyped foo);

// build.hxml
--macro includeFile('imports.js')
-main Main
-js main.js

But if you want to buy into es modules a little more you can also try genes which will import regular @:jsRequire through module syntax.

1 Like

I made a little macro to turn

@:build(Import.from('./foo.js')) 
extern class Foo {
  static public function ho():Int;
}

@:build(Import.from('./foo.js', 'bar')) 
extern class Bar {
  static public function ha():Int;
}

@:build(Import.from('./beep.js')) 
extern class Beep {
  static public function bop():Int;
}

Into the following preamble:

import * as $module0 from "./beep.js";
import * as $module1 from "./foo.js";
var Beep = $module0;
var Bar = $module1.bar;
var Foo = $module1;

No idea if it’s correct (can’t test on try.haxe and don’t want to invest any more time), but should get you started :wink:

2 Likes

Thanks guys for your answers !

Yes there are many ways to achieve it but as Cedric said, it would be nice if we could get a Haxe raw synthax or something like that in pure Haxe to deal with all that in near future !