The standard way to detect whether NodeJS module was called directly (via CLI) or required by another module is to use
module === require.main
.
When using Webpack both that objects do not refer to the original objects module
and require.main
provided by NodeJS, as we expect by default.
See this issue
npm i --save is-main-module
- Make sure you have set
externals: [nodeExternals()]
in your Webpack config. - Check if your module is required by another one with
!isMain()
. In addition you can get refs to thismodule
andrequire.main
const thisModule = require('is-main-module');
const isThisModuleRequired = thisModule.!isMain();
const isThisModuleMain = thisModule.isMain();
const refToThisModule = thisModule.moduleRef;
const refToMainModule = thisModule.mainRef;