javascriptnode.jses6-modules

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


Solution

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