0

In my application I have my javascript in files. I am trying to convert those files to javascript modules.

I need to have some code in my html (in order to generate Django urls - (see this question How to configure a django url correctly in javascript).

html

<html>
    <head>
    </head>
    <body>
        <p id="display_text">aaa</p>
    </body>

    <script type="">
        function setText(text) {
            var display_text = document.getElementById('display_text');
            display_text.innerText = text;
        }
    </script>
    <script type="" src="module.js"></script>
</html>

module.js

setText('module')

This does not seem to work with modules

If I convert the html as follows

<script type="module">
    export function setText(text) {
        var display_text = document.getElementById('display_text');
        display_text.innerText = text
    }
</script>
<script type="module" src="module.js"></script>

I get the error

module.js:1 Uncaught ReferenceError: setText is not defined

If I need to import the setText function into module.js, how do I do it?

What am I doing wrong?

Psionman
  • 3,084
  • 1
  • 32
  • 65
  • 2
    Does this answer your question? [How to use code from script with type=module](https://stackoverflow.com/questions/49338193/how-to-use-code-from-script-with-type-module) – Ouroborus Sep 30 '21 at 07:26
  • @Ouroborus I don't think it's quite the same. I understand the need to import, but how can I import a function from an HTML page? – Psionman Sep 30 '21 at 07:44
  • Yes it seems you have to import from a file. There is import by name or ID as far as I can see. Maybe that means you can only put modules in files. [MDN docs: javascript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) – Peter Krebs Sep 30 '21 at 07:57
  • You can only import into or export from modules. Use a global scope (such as `window.something`) to share data between modules and non-modules. For example, from within the module, `window.setText = setText;`. (Also, modules can't be inlined. They need to be a separate file and you need to be using `https`.) Ideally, you're using all modules or no modules. – Ouroborus Sep 30 '21 at 08:15
  • @Ouroborus Yes. Reluctantly I've decided to revert to no modules – Psionman Sep 30 '21 at 08:37

0 Answers0