How do I do if (require.main === module)

You know how in JavaScript, if you put:

if (require.main === module) {
    // only run if you go 'node file.js'

How do I do that in ReScript?

I didn’t know about this, actually, but there aren’t any built-in techniques for it. The only way is using %raw.

if %raw(`require.main === module`) {
1 Like

Interesting, I had not known that either. If I had to think of a more ‘ReScript-y’ way of detecting if this is a script running in Node.js, I’d probably look for the existence of a process variable and run based on that. There’s special support for that: Bind to Global JS Values | ReScript Language Manual


let isNode = switch %external(process) {
  | Some(_) => true
  | None => false

The check require.main === module won’t work in browsers, it’s nodejs code. What it’s doing is detecting whether the code was loaded by another module or directly invoked via node file.js.

I only just learned this technique too after someone updated some scripts I wrote :laughing: It didn’t make a real difference.

I like the raw option.

Thanks, I believe interfacing with JavaScript this way was the first thing I learned in ReScript. Clearly it didn’t stick, lol.