Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 318
Dietrich Epp Avatar asked Oct 03 '20 03:10

Dietrich Epp


1 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.

like image 114
Take-Some-Bytes Avatar answered Oct 05 '22 16:10

Take-Some-Bytes