如何确定 javascript 模块是通过脚本 src 导入还是加载的?

how to determine if javascript module was imported or loaded via script src?

假设我有一个名为 module.js:

的模块
export default function greet() { console.info( 'hello' ); }

module.js 中(在函数 greet 内部或外部),如何确定模块是否使用以下方式加载:

<script type=module src="./module.js">

对比:

<script type=module>
import greet from './module.js';
</script>

无论哪种方式,import.meta 是相同的,document.currentScriptnull,而 NodeJS 的 require(因此 require.main)和 module 都是 undefined.

谢谢!

当您导入任何模块时(使用 import<script type="module">),即使您从多个地方导入该模块,模块的主体也只会计算一次。

因此,以下内容:

//module.js
console.log('I was imported')
<script type="module">
  import './module.js'
</script>
<script type="module" src="./module.js"></script>

...只会记录 I was imported 一次。

由此可见,一个模块可以同时以多种方式导入,所以不能确定模块导入方式的任何方法...

...只要您不使用导出。

使用脚本标签包含模块与 import 'modulepath' 语法相同,即 in MDN's words仅针对其副作用导入模块 .

这意味着,没有导出,只是评估模块。

但是,如果使用了其中一个导出(例如调用),则可以排除使用导出的模块实例是由脚本标记导入的可能性。

不过,以下情况仍然可能发生:

//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 -->