Search code examples
javascripthtmlimportwebstorm

Javascript file with module import does not work


I'm doing a small learning project on and came across the fact that when I add import to a js script, it seems to start being ignored and not executed. I don't quite understand if the problem is in the code or in WebStorm.

I wrote a simplified example, but it didn't work either.

test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>Hello world!</div>
<div id="display"></div>
<script type="module" src="./main.js"></script>
</body>
</html>

main.js

import {print} from "./func";
print();

func.js

export function print(){
    document.getElementById("display").innerHTML += "Hello";
}

All files are in the same folder.


Solution

  • Your import statement in main.js is just slightly off. You should change

    import { print } from "./func";
    

    to:

    import { print } from "./func.js";