如何确定是否通过脚本src导入或加载了javascript模块? [英] how to determine if javascript module was imported or loaded via script src?

查看:59
本文介绍了如何确定是否通过脚本src导入或加载了javascript模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I have a module named module.js:

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

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

Within module.js (either inside or outside of function greet), how can I determine whether the module was loaded using:

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

与之相对:

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

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

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 < script type ="module"> ),即使您从多个位置导入该模块,该模块的主体也只会被评估一次.

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.

因此,以下内容:

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

由此,我们可以清楚地看到一个模块可以同时以多种方式导入,因此,不可能以任何方式确定如何模块已导入...

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.

使用脚本标签包含模块与 import'modulepath'语法相同,即

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.

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

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

这篇关于如何确定是否通过脚本src导入或加载了javascript模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆