Closed jamesnw closed 8 months ago
I'm still not very excited about using the working directory instead of require.main.filename
, since the two are fairly meaningfully different. I'd generally prefer to suggest that users manually fall back on process.cwd()
, since that's at least explicit, rather than doing it silently if we can't determine the entrypoint.
From https://github.com/nodejs/node/issues/49440, it looks like we can get this information from process.argv[1]
, although it needs to be massaged somewhat because of the wide range of different ways an entrypoint can be specified on the command line. Specifically, https://github.com/nodejs/node/issues/49440#issuecomment-1703467948 suggests module.createRequire(process.argv[1]).resolve(process.argv[1])
, which I believe should work for our use-case. (If process.argv
isn't defined, we should just fall back on throwing an error.)
See https://github.com/sass/sass/issues/3792
In addition to #2176, we are seeing that
require.main
is undefined in an ESM context. This means that@JS("require.main.filename")
is throwing the error `reading "filename" of undefined, which throws before the more helpful error can be thrown-Optional chaining is not supported by
@JS
syntax, but I was able to find a workaround in https://github.com/sass/dart-sass/pull/2179.The second more significant issue is that, currently, because of this,
entryPointDirectory
is required in anESM
context.An equivalent to
require.main.filename
in ESM,import.meta.filename
is added in Node 21. However, even if we waited until that was available, because the mainsass.dart.js
file is CommonJS, we won't have access to that. From the Node docs-When the entry point is not a CommonJS module, require.main is undefined, and the main module is out of reach.
My proposal would be to use the current directory as a fallback when
require.main.filename
is not defined. It is not identical to the concept ofrequire.main.filename
, but does cover the most common case where the user is running the command from the directory that contains the package.I confirmed that
p.dirname(p.absolute('.'))
as the fallback for whenrequire.main.filename
is not defined allows aNodePackageImporter()
to be used without setting anentryPointDirectory
in ESM, but wanted to verify that's the correct path forward before committing.I think we had discussed the possibility of
require.main
not being available at one point, but had thought that the fixes made todart_cli_pkg
would address this as well.