1

If I export from an JavaScript module that's inline in my HTML as in <script type="module"> …inline code here… </script> is there any way I can reference that module, and import it from another module?

My JS app has some generated code/configuration which would be quite convenient to rendering dynamically within some already-outgoing HTML instead of creating a separate new endpoint just for that data.

Using Django template syntax as a rough example, and generating JS code in a not particularly production-grade way just to keep it simple, consider if I had some "template.html":

<script id="config_module" type="module">
const configData = {
   field1: "{{ something }}",
   field2: [{% for n in someother %}{{ n }}, {% endfor %}]
};

export default configData;
</script>

<script type="module" src="{% static "myapp/main_code.mjs" %}"></script>

Where the content of "myapp/main_code.mjs" would be something like:

import config from "#config_module";     // ← ???

if (config.field1 === "whatever") alert("Something was whatever!");

I can think of other ways to accomplish something similar, such as:

  • have the inline module assign a global variable like window.myPrefix_config = { … } for the other module to grab (see How to use code from script with type=module for example)
  • avoid the inline JS and give that content its own separately-rendered URL to import config from "/server/generates/config.mjs" where needed

But I am curious about the underlying question itself here: when I define a module inline is there any way to import it from other modules in the same browser context? Or in terms of the HostResolveImportedModule spec, do browsers support any sort of ModuleSpecifier syntax that can resolve to an inline script, a working version of my import … from "#config_module" pseudocode?

natevw
  • 16,807
  • 8
  • 66
  • 90

0 Answers0