How do I detect if an ES Module is the main module?

Viewed 1442
2 Answers

You could use es-main.

From the package README:

import esMain from 'es-main';
 
if (esMain(import.meta)) {
  // Module run directly.
}

NOTE: This module will only work in a Node.JS environment, because the module code uses native Node.JS modules.

In the browser I don't know, but in node with .mjs module the following seems to work :

const isMainModule = import.meta.url.endsWith(process.argv[1])

Explanation:

import.meta.url begins with the protocole file:// eg:

file:///path/to/my/module.mjs

but in node, process.argv[1] is shorter, eg:

/path/to/my/module.mjs

so endsWith is useful here.

Related