Access variables defined in script tag with type module?

自作多情 提交于 2020-06-23 06:49:17

问题


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>

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


回答1:


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.



来源:https://stackoverflow.com/questions/51547745/access-variables-defined-in-script-tag-with-type-module

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