I'm currently trying to migrate some projects over to ESM but I'm hitting an issue where a module is (rightfully) expecting to be able to access require.main.filename. I was surprised to see that the require passed into modules inside node_modules isn't the vanilla one.
Is it possible to get a dummy value that looks close enough to the real require.main?
Yep, it's totally possible. In this case we were incorrectly assuming the main script would be ESM so not exposing it, but the good news is we have all the stuff in place to expose it.
Update:
Thanks @specialkk!
I'll pay the unit test debt in the AM.
Update:
v0.23.3 is released 馃帀
This doesn't seem to be working. Like #320, I was trying to do a require.main === module or process.mainModule === module, but in esm .js not .mjs.
I added { cjs: { vars: true }} in my esmrc file to bring module back. That part works for me, great.
But now I'm having trouble with the other half of this check. I'm on 3.0.84, trying to run node -r esm myFile.js. Both process.mainModule and require.main are showing up as undefined.
As a fallback, I'm using `file://${__filename}` === import.meta.url. I'd rather test the module rather than the filename, but this at least got me unblocked. Any idea what I might try or what I could do to get require.main?
Hi @rektide!
I can't reproduce locally (on master branch).
// foo.js
console.log(process.mainModule)
console.log(require.main)
then node -r esm ./foo will log both objects. Note { cjs: { vars: true }} is on by default so no need to explicitly enable it.
Most helpful comment
Yep, it's totally possible. In this case we were incorrectly assuming the main script would be ESM so not exposing it, but the good news is we have all the stuff in place to expose it.
Update:
Thanks @specialkk!
I'll pay the unit test debt in the AM.
Update:
v0.23.3 is released 馃帀