scottredig / zig-javascript-bridge

Easily call Javascript from Zig wasm
MIT License
38 stars 2 forks source link

Add support for generating a javascript module #11

Open noxabellus opened 3 months ago

noxabellus commented 3 months ago

Most use of javascript today utilizes the module syntax, rather than declaring global variables. Support is now pretty much ubiquitous, and many projects use bundlers like webpack anyway, which understand the module syntax as well. The global variable export is still useful for some situations, but it would be nice to have a flag that can be passed to generate_js to allow the creation of a module instead. Perhaps a module could be the default, even. Alternatively, the generate_js cli could also just detect whether the output file extension is .js or .mjs and switch on that instead of a flag.

In any case, the required change would be fairly simple.

The existing definition created here could be rewritten as:

try writer.writeAll("class ");
try writer.writeAll(args[2]);
try writer.writeAll(
  \\ {
  ...

This would not change the existing semantics as far as I'm aware.

Then, configuration based on the flag/file extension could guard a small addition proceeding those lines:

if (makeModule) {
  try writer.writeAll("export default ");
}
noxabellus commented 3 months ago

Another consideration:

There might be a future desire to optionally produce a common-js style module, that can be imported with common's (more specifically node's) require. This would require a more substantial modification to the generator, and perhaps it would be best to take care of both additional use cases at once.