Based on this it is possible for JS module code to determine whether it is being run directly or being imported from somewhere else. This is analogous to the old way of doing it but module is not a thing anymore in the EcmaScript Modules world? Or is it?
So, I wanted to take it a step further and use this as an opportunity to learn a few things under the hood.
I tried this
#!/usr/bin/env node
import url from "url";
const code = `
console.error(
"isScript debug: x:", import.meta.url, " y:", url.pathToFileURL(process.argv[1]).href
);
return import.meta.url === url.pathToFileURL(process.argv[1]).href;
`;
const f = Function(code);
export const isScript = () => f();
... as an attempt to not use eval
which is "evil". Basically I want to be able to incorporate this logic in my scripts without having to write the import.meta.url === url.pathToFileURL(process.argv[1]).href
code in each place that I need it. Because of two reasons, (1) it's just difficult to remember, and (2) making ridiculously tiny "libraries" is trendy with JS. But i realize that this may be challenging due to the "special" nature of import
.
Indeed this code does not run: SyntaxError: Cannot use 'import.meta' outside a module
Is this a fool's errand? I could at least still make an isScript
which has to receive an import.meta.url
value, right? The thing is, that'd be a mildly ~leaky abstraction~ (not sure what term to use here) and rather unsatisfactory.
By the way, eval
also does not work, the code "compiles" but when importing this module and trying to run it, I get SyntaxError: Cannot use 'import.meta' outside a module
from the importing code. I might be doing something silly though.