使用类型模块访问脚本标记中定义的变量? [英] Access variables defined in script tag with type module?

查看:113
本文介绍了使用类型模块访问脚本标记中定义的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的HTML中具有带有type模块的script标记,并且它会导出一个变量:

I have a script tag inside my HTML with type module, and it exports a variable:

<script type="module">
  var life = 42;
  export { life };
</script>

如何从其他脚本标签或Chrome控制台访问life进行调试?

How do I access life from other script tags or the Chrome console for debugging?

推荐答案

首先,您应该使用 import 适用于html文件.但是,对于另一个js文件中的单独js文件,您可以仅使用import {life} from 'path/to/file'加载变量.如果它嵌入在html中,并且您在同一页面中使用脚本,则不需要export,并且只需使用变量life即可访问life.实际上,type="module"实际上阻止访问script标记中定义的变量.如果要访问同一页面上的变量,则应将其删除.页面上的开发者控制台也是如此.

First of all, you should be using export in separate js files and not embedded in an html file. I'm not sure if import works on html files. However, for a separate js file in another js file you can just use import {life} from 'path/to/file' to load the variables. If it's embedded in html and you use scripts in the same page, you do not need the export and you can access life simply by using the variable life. In fact, the type="module" actually prevents variables defined in the script tag from being accessed. If you want to access the variables on the same page then you should remove it. The same applies for the developer console on the page.

这篇关于使用类型模块访问脚本标记中定义的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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