[英]how to determine if javascript module was imported or loaded via script src?
Suppose I have a module named module.js
:假设我有一个名为
module.js
的模块:
export default function greet() { console.info( 'hello' ); }
Within module.js
(either inside or outside of function greet
), how can I determine whether the module was loaded using:在
module.js
(在 function greet
内部或外部),我如何确定模块是否已使用:
<script type=module src="./module.js">
versus:相对:
<script type=module>
import greet from './module.js';
</script>
Either way, import.meta
is the same, document.currentScript
is null
, and NodeJS's require
(and therefore require.main
) and module
are both undefined
.无论哪种方式,
import.meta
是相同的, document.currentScript
是null
,并且 NodeJS 的require
(因此require.main
)和module
都是undefined
。
Thanks!谢谢!
When you import any module (either using import
or <script type="module">
), the body of the module will be evaluated only once, even if you import that module from multiple places.当您导入任何模块(使用
import
或<script type="module">
)时,模块的主体将仅被评估一次,即使您从多个位置导入该模块也是如此。
So, the following:因此,以下内容:
//module.js
console.log('I was imported')
<script type="module">
import './module.js'
</script>
<script type="module" src="./module.js"></script>
...will log I was imported
only once. ...将记录
I was imported
一次。
From that, we can clearly see that a module may be imported multiple ways at the same time , so there can not be any way to determine the way how a module was imported...由此我们可以清楚地看到一个模块可能同时被多种方式导入,因此无法确定模块的导入方式......
...as long as you don't use exports. ...只要您不使用导出。
Including a module using a script tag is identical to the import 'modulepath'
syntax, that is, in MDN's words , importing a module for its side effects only .使用脚本标签包含一个模块与
import 'modulepath'
语法相同,也就是说, 用 MDN 的话来说,导入一个模块只是为了它的副作用。
That means, that no exports are taken, the module is just evaluated.这意味着,不进行任何导出,只评估模块。
However, if one of the exports is used (called, for example) you can rule out the possibility that the module's instance that used the export was imported by a script tag.但是,如果使用了其中一个导出(例如调用),您可以排除使用导出的模块实例是由脚本标记导入的可能性。
The following scenario is still possible, though:但是,以下情况仍然是可能的:
//module.js
export default function greet() {
console.info('hello'); //<-- This must have been called from an `import` import
}
<script type="module">
import greet from './module.js';
greet() //imported by `import`
</script>
<script type="module" src="./module.js"></script> <!-- imported by script tag -->
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.