如何确定是否通过脚本src导入或加载了javascript模块?

安德鲁·M·安德鲁斯三世

假设我有一个名为的模块module.js

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

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

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

与:

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

无论哪种方式,import.meta都是一样的,document.currentScriptnull和的NodeJS的require(因此require.main)和moduleundefined

谢谢!

防区

导入任何模块(使用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一次。

从这一点,我们可以清楚地看到,一个模块可以导入多种方式在同一时间,所以不能被任何方法来确定一个模块是如何进口的方式......

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

使用script标签包含模块与import 'modulepath'语法相同,也就是说,以MDN的话来说仅出于副作用导入模块

这意味着,不进行导出,仅对模块进行评估。

但是,如果使用了一种导出(例如,称为导出),则可以排除使用脚本标记导入使用导出的模块实例的可能性。

但是,以下情况仍然可行:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在模块内以编程方式确定javascript模块是否通过脚本src加载(未导入)

确定是否通过NodeJS模块直接调用脚本

如何使用Javascript / jQuery确定是否已加载图像?

您如何确定大写锁定是否在使用JavaScript?

如何确定是否已声明Javascript类?

如何确定是否使用 bash 脚本以 root/sudo 身份运行脚本/命令

如何确定是否以及哪个Linux安全模块(LSM)可用?

如何以编程方式(在Shell脚本中)确定是否有更改?

如何确定是否已在Inno Setup Pascal脚本中构造了对象?

如何确定是否ZonedDateTime是“今天”?

angular如何确定是否存在jQuery?

如何确定是否存在JMS Connection?

scanf如何确定是否阻止?

如何确定是否可以看到组件?

如何确定是否启用了沙箱

如何确定是否禁用Windows凭据

如何确定是否需要“本地复制”

如何确定是否单击了地图或标记

如何确定是否显示 tableViews 页脚?

如何确定是否存在类方法

如何确定是否选择了可选列表

如何确定是否为Selenium + Python加载了一些HTML元素?

我是否可以确定是否从终端运行Perl脚本?

如何确定是否通过批处理安装了Office 2010 SP2?

如何确定页面是否通过JavaScript安全?

如何确定是否存在正在监听键盘事件的Javascript代码?

如何知道是否已加载JavaScript(脚本)?

如何重新加载脚本的src

Javascript-使用按钮确定是否在线