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

How can I detect if an ECMAScript module is the main module? This is easy for CommonJS modules (see Detect if called through require or directly by command line).

  • There is no require or require.main

  • No process.mainModule

  • The import.meta has no clues, only has url



Solution 1:[1]

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.

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Take-Some-Bytes
Solution 2 Joseph Merdrignac