javascripthtmlmodule

Simple JS module import in HTML won't work


I'm trying to get an understanding of module imports in JS. I read a lot of tutorials and documents on the web and I fell like I have a grasp of the theory now, but still I can't make things work in practice.

So, here's what I've done.

I got three files in the same path:

try1.html
try2.html
f.js

try1.html:

<!-- try1.html -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Try1</title>
</head>
<body>

    helloooo

    <script type="module">

        import {printHello} from './f.js';

        document.body.appendChild(printHello());

    </script>
</body>
</html>

try2.html:

<!-- try2.html -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Try2</title>
</head>
<body>

    helloooo

    <script>

        function printHello() {
            let p = document.createElement('p');
            p.style = 'background: red'
            p.textContent = 'helloooooooooooooo';
            return p;
        }

        document.body.appendChild(printHello());

    </script>
</body>
</html>

f.js:

// f.js

function printHello() {
    let p = document.createElement('p');
    p.style = 'background: red'
    p.textContent = 'helloooooooooooooo';
    return p;
}

export {printHello};

You can see that what I'm trying to do is simply to call a function which will create a DOM element and attach it to the document.

If I do that in a script tag inside the html file, it works (as in try2.html case); instead, if I define the function inside the f.js file and then import it in the try1.html file, it won't work (that is, the "helloooooooooo" red text won't show up).

It's all vanilla javascript and html, as I'm not using Node.js or anything and I'm loading the page simply opening the html file in the browser (firefox, for reference).

What is it I'm doing wrong? I can't get my head around it. Please help!


Solution

  • the problem is some browsers don't support importing modules from local files, clicking on the html file in the browser won't work, if you use vscode you can install an extension called "Live Server", or if you don't use vscode try to use a live server.

    Here is the website by simply clicking on the file

    And this by using a live server