javascriptimport

import statement in javascript


I have html code with javascript inside a django project:

<body>
<-- some html>
</body>
<script>
import fs from "fs"
// some javascript
</script>

Now I get the error import declarations may only appear at the top level of a module.

What am I doing wrong? And is there some reference that explains how the import works in javascript? I'm not used to javascript yet and in all other languages I never had an issue with import statements.


Solution

  • By default, <script> tags are interpreted as regular scripts, not as ES6 modules. Specify the script as a module using the type="module" attribute.

    <body>
    <-- some html>
    </body>
    <script type="module">
    import fs from "fs";
    /* fs cannot be imported in browser environment
    since it is a Node.js standard lib */
    // some javascript
    </script>