haxe icon indicating copy to clipboard operation
haxe copied to clipboard

[js] ESM import syntax support

Open haxiomic opened this issue 3 years ago • 7 comments

JavaScript's native import syntax is gaining support and usage – the latest version of three.js no longer supports require() for some modules and so presently cannot be used with haxe https://github.com/haxiomic/dts2hx/issues/110

Haxe currently has @:jsRequire which when added to externs, generates require() calls for module imports

I think we could add @:jsImport (or @:js.import) which would generate import statements instead. For example:

@:jsRequire("three/examples/jsm/controls/OrbitControls", "OrbitControls") extern class OrbitControls {
// generates
var three_examples_jsm_controls_orbitcontrols_OrbitControls = require("three/examples/jsm/controls/OrbitControls.js").OrbitControls;

This would become

@:js.import("three/examples/jsm/controls/OrbitControls.js", "OrbitControls") extern class OrbitControls {
// generates *at top of file*
import { OrbitControls as three_examples_jsm_controls_orbitcontrols_OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

Or as Simn suggests, this may be better as

@:js.import("OrbitControls", "three/examples/jsm/controls/OrbitControls.js") 

To mirror the js import syntax

haxiomic avatar Mar 08 '22 10:03 haxiomic

Shouldn't the order of arguments follow JS here?

Also, I hate JS.

Simn avatar Mar 08 '22 11:03 Simn

FWIW here's a macro based implementation: https://github.com/back2dos/jsImport#jsimport---use-es6-imports-in-haxe

Never actually used it in production, so I can't vouch for it, but I think it highlights the three different cases rather well (as for the corresponding Haxe syntax, I'll leave you to judge its suitability).

back2dos avatar Mar 08 '22 13:03 back2dos

@back2dos thanks for the link! Can confirm it works well, I had to add a variant where you specify the exportName: https://github.com/back2dos/jsImport/pull/1 but otherwise it's perfect

@sonygod: try this:

Install @back2dos's jsImport

haxelib git jsImport https://github.com/haxiomic/jsImport

Add it to your build arguments

--library jsImport

And replace @:jsRequire with @:js.import, for orbit controls:

@:js.import("three/examples/jsm/controls/OrbitControls.js", "OrbitControls") extern class OrbitControls {

Notice we've also added .js to the file path

haxiomic avatar Mar 08 '22 13:03 haxiomic

If everyone agrees that the jsImport approach is good, I can port that to the compiler. I don't think we have to reinvent any wheels here.

Simn avatar Mar 26 '22 11:03 Simn