browser - how to determine if javascript module was imported or loaded via script src? - Stack Overflow

admin2025-04-19  0

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!

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!

Share asked May 14, 2020 at 6:46 user210158user210158
Add a ment  | 

1 Answer 1

Reset to default 4

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 -->
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745070567a283251.html

最新回复(0)