0

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.

Steven Lu
  • 41,389
  • 58
  • 210
  • 364
  • As indicated by error messages (and you've only had the first), the approach to producing an `isScript` function taken in the post is likely doomed - how would it ever have access to the `import.meta` object of a caller given modules operate in their own name space and do not create global variables. Could you elaborate (in the question please) on the concern "that'd be a mildly leaky abstraction and rather unsatisfactory"? Potentially a response to the concern may be the most effective solution to the issue raised.. – traktor Mar 17 '22 at 00:47
  • I'm probably definitely using the wrong term when i refer to it as a "leaky abstraction". Will edit. – Steven Lu Mar 17 '22 at 16:24

0 Answers0