如何在模块内以编程方式确定javascript模块是否通过脚本src加载(未导入) [英] how to programmatically determine, within the module, if javascript module was loaded via script src (not imported)

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

问题描述

假设我有一个模块:

  // module.js 
export默认函数greet(){console.info('hello'); }

如果模块通过以下方式加载:



< pre class = lang-html prettyprint-override> < script type = module>来自 ./module.js的
问候;
...
< / script>

然后我希望调用代码能够调用 greet()本身,而不会自动调用它(正常情况)。



但是,如果通过以下方式加载模块:

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

然后我要模块调用 greet()立即(作为加载的副作用)。



我该怎么做?

解决方案

不幸的是,这个问题与您的上一个有相似的答案:确实是



模块可以导出内容,但是它们对进口商如何使用(以及用什么方式)不负责。



模块被创建为独立且可重用,即使在同一页面上也无需重新评估:



对该模块的代码进行一次评估,然后将其导出传递到将其导入的每个位置。



这种设计是好的,但实际上使模块无法确定




另一方面,<脚本type = module> 语法也不是引发了这一点:这是一种通过HTML向浏览器发出 main (又名HTML)信号的方式。 顶级)模块,可自行加载其依赖项(子模块)。






部分解决方案:



制作一个单个顶级模块,该模块导入其他所有内容并通过副作用操作页面,并避免通过脚本标签导入其他模块。此外,我建议您避免在非顶级模块中产生副作用,而应专注于出口。



如果有人真的想从他们的模块中导入您的模块HTML,他们仍然可以这样做:

 < script type = module>来自 ./module.js的
问候;
greet();
< / script>


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

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

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.


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:

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

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

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