skip to Main Content

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.

2

Answers


  1. 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>
    
    Login or Signup to reply.
  2. </body> //use this approch <script type="module"> import fs from "fs"
    //YOUR CODE HERE

    //or either use this
    `<script type="commonjs">
        const fs = require('fs')`
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search