我想检查我的模块是否被包含或直接运行.我怎么能在node.js中这样做?
如何检测 ECMAScript 模块是否为主模块?这对于 CommonJS 模块来说很容易(请参阅检测是否通过 require 调用或直接通过命令行调用)。
没有require或require.main
不process.mainModule
没有任何线索import.meta,只有url
是否可以检查JavaScript文件是否正在直接运行,或者是否需要将其作为es6模块导入的一部分。
例如,包含一个主脚本。
// main.js
import './other';
if (mainTest){
console.log('This should run');
}
Run Code Online (Sandbox Code Playgroud)
导入依赖项。
// other.js
if (mainTest){
console.log('This should never run');
}
Run Code Online (Sandbox Code Playgroud)
包括<script src=main.js></script>应该导致来自main.jsother.js 的控制台消息,但不会导致。