When writing a Deno
script, sometimes they could be a executed from the command line using deno run
but at the same time may contain libraries that can be consumed through an import from another script.
What is the proper way to do this in Deno.
The equivalent in Python would be to put at the bottom of the script:
if __name__ == '__main__':
main(sys.argv[1:])
How should this be done in Deno
?
Deno has a flag available at runtime called import.meta.main
. Here is an example of how it should be used in a script:
if (import.meta.main) main()
// bottom of file
From the docs:
Deno supports a number of methods on the import.meta API:
import.meta.url: returns the URL of the current module.
import.meta.main: returns whether the current module is the entry point to your program.
import.meta.resolve: resolve specifiers relative to the current module.
Note: import
namespace is not available in the Deno REPL at v1.0.0