假设我有一个名为的模块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.currentScript
是null
和的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
一次。
从这一点,我们可以清楚地看到,一个模块可以导入多种方式在同一时间,所以不能被任何方法来确定一个模块是如何进口的方式......
...只要您不使用导出。
使用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] 删除。
我来说两句