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

China☆狼群 提交于 2020-05-31 04:29:29

问题


Suppose I have a module named 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:

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

Thanks!


回答1:


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.

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.

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.

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


来源:https://stackoverflow.com/questions/61790963/how-to-determine-if-javascript-module-was-imported-or-loaded-via-script-src

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!