Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access variables defined in script tag with type module?

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?

like image 330
David Song Avatar asked Sep 11 '25 09:09

David Song


1 Answers

This seems to be highly ranked in SEO and the real answer from @Aplet123 is a little buried in the comments.

  1. You cannot access variables across/outside of modules, this is the whole point. You can export/import but this won't work in the browser console.

  2. You can attach any object to window in order to expose it globally. So adding window.life = life will expose life (or window.life) in the browser console.

This is a solid option when you're playing around or debugging issues.

This shouldn't be used in production except under limited circumstances – for example if you need to load JavaScript without access to the network (including through a ServiceWorker) or you want the code to be in one file to be easily inspected.

like image 56
AxelTheGerman Avatar answered Sep 14 '25 01:09

AxelTheGerman