`if __name__ =='__main __'`在javascript es6模块中相当 [英] `if __name__ == '__main__'` equivalent in javascript es6 modules
本文介绍了`if __name__ =='__main __'`在javascript es6模块中相当的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以检查JavaScript文件是直接运行还是作为es6模块导入的一部分。
Is it possible to check if JavaScript file is being run directly or if it was required as part of an es6 module import.
例如,包括主脚本。
// main.js
import './other';
if (mainTest){
console.log('This should run');
}
导入依赖。
// other.js
if (mainTest){
console.log('This should never run');
}
包括< script src = main.js> < / script>
应该导致来自 main.js
而不是other.js的控制台消息。
including <script src=main.js></script>
should result in the console message from main.js
but not other.js.
我发现关于此问题的回答节点,但我专门针对es6导入感兴趣
I found the answer to this question with regards to node, but I am interested specifically for es6 imports
推荐答案
module.parent
将帮助您:
module.parent
will help you:
if(module.parent) {
console.log('required module')
} else {
console.log('main')
}
这篇关于`if __name__ =='__main __'`在javascript es6模块中相当的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文