[英]how to programmatically determine, within the module, if javascript module was loaded via script src (not imported)
Suppose I have a module:假设我有一个模块:
// module.js
export default function greet() { console.info( 'hello' ); }
If the module is loaded via:如果模块是通过以下方式加载的:
<script type=module>
import greet from './module.js';
...
</script>
then I want the calling code to be able to invoke greet()
on its own, without it being called automatically (the normal scenario).然后我希望调用代码能够自己调用
greet()
,而不是自动调用它(正常情况)。
However, if the module is loaded via:但是,如果模块是通过以下方式加载的:
<script type=module src="./module.js"></script>
then I want the module to invoke greet()
immediately (as a side-effect of being loaded).然后我希望模块立即调用
greet()
(作为加载的副作用)。
How can I accomplish this?我怎样才能做到这一点?
Unfortunately, this question has a similar answer to your previous one : it isn't possible.不幸的是,这个问题与您之前的问题有相似的答案:这是不可能的。
Modules may export things, but they aren't responsible for how (and which) do the importers use (of) them.模块可以导出东西,但它们不负责导入器如何(以及哪些)使用它们。
Modules are created to be separate and reusable , even on the same page, without re-evaluation:模块被创建为独立且可重用的,即使在同一页面上,也无需重新评估:
The module's code evaluated once, then its exports are passed to every place that imports it.模块的代码评估一次,然后将其导出传递到导入它的每个地方。
That design is good, but essentially makes impossible for a module to determine anything about its importers.这种设计很好,但本质上使模块无法确定有关其导入器的任何信息。
On the other hand, the <script type="module">
syntax also wasn't designed for that: it's the way to signal the browser through HTML the main (aka. " top-level ") module, that loads its dependecies (sub-modules) on its own.另一方面,
<script type="module">
语法也不是为此而设计的:它是通过 HTML主(又名“顶级”)模块向浏览器发出信号的方式,该模块加载其依赖项(子模块)自己。
Partial solution:部分解决方案:
Make a single top-level module, that imports everything else and operates the page by "side effects", and avoid importing other modules by script tags.制作一个单一的顶级模块,导入其他所有内容并通过“副作用”操作页面,并避免通过脚本标签导入其他模块。 Moreover, I recommend you to avoid side effects in the non-top-level modules, and focus on exports instead.
此外,我建议您避免在非顶级模块中产生副作用,而将重点放在导出上。
And if someone really wants to import your module from their HTML, they can still do this instead:如果有人真的想从他们的 HTML 导入你的模块,他们仍然可以这样做:
<script type="module">
import greet from './module.js';
greet();
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.