Check me here... I can't use require() if I'm in a JS module (ReferenceError) but I can't use import if I'm *not* in a module (SyntaxError)

How am I supposed to reliably load something if this file needs to be used in both contexts??? Losing my marbles

Related, did you know that running

new Response(new Blob([binary], { type: 'application/wasm' }));

will cause some random WebAssembly (large!) module to be compiled? Not even the one in `binary`!

oh this is unhinged

await WebAssembly.compile(Buffer.from(require('./xyz.wasm.js'), 'base64'))

where xyz.wasm.js is a js module that does module.exports = 'some_base64_string'

look at me i'm a Real Engineer
@tekknolagi uh, what's your build system? Is this straight node, webpack, browser?

@gcampax all of the above, probably; I'm doing some dynamic instrumentation of a bunch of existing packages and then running them

Maybe when I'm injecting code I should check for require(/import in the source code...

@tekknolagi you should at least check for the "module" field in package.json, if it's a node compatible module it will tell you if it's commonjs (require) or esm (import). Alternatively, you can do dynamic import() - that always works.
@gcampax it always works except not all my uses of it can be async-ified all the way to the top level. If you have a way to somehow turn it sync again, I'm all ears...

@tekknolagi no there is no way because loading a module itself is async: modules have top-level await. So you need to make everything async.

The best solution is probably using a bundler like webpack that supports both import and require and doesn't care too much about the package type...

Or you can turn commonjs modules into exporting a top level async function that returns the exports themselves, and rewrite all uses of require to be async. That's essentially what the bundler would do...

@gcampax yeah I don't think I can do that in this use case. I think I'm going to try and auto detect and fail quietly if it doesn't work out :/
@gcampax it's a very messy situation and I have no idea what I'm doing on top of that
@tekknolagi btw I'm assuming this is to load your instrumentation runtime? Another option could be to put a __require function in the global object that you preinitialize before you load the first module and use that...
@tekknolagi yeah this situation sucks, my condolences
@tekknolagi in vanilla node at least, you should be able to use dynamic import() syntax in a commonjs module IIRC. just not the static “import xyz from ‘foo’” syntax.