Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

216
Vistas
Making a function to return whether the current code is being run directly or being imported, without using eval

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.

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda