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?

5
  • 2
    Does this answer your question? How to use code from script with type=module Commented Sep 30, 2021 at 7: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? Commented Sep 30, 2021 at 7: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 Commented Sep 30, 2021 at 7: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. Commented Sep 30, 2021 at 8:15
  • 1
    @Ouroborus Yes. Reluctantly I've decided to revert to no modules Commented Sep 30, 2021 at 8:37

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.