0

Javascript file:

class Person2
{
    constructor(name, age) {
        this.name = name;
        this.age = age;
      }

      getName() {
        return this.name;
      }
      getAge() {
        return this.age;
      }
}

export default Person2;

Html with javascript:

<script type="module" src="Assets/testfunction.js">
    import pers from "./testfunction.js";
     
    let p  = new pers("1", 1);

    console.log(p.getAge());
    
</script>

If I remove type="module", I just get exceptions that there isn't a reference to pers, but when I include it, the code doesn't run. If I make it a simple script tag with just a console.log inside of it, it will run, and print.

Somecode
  • 15
  • 1
  • 4
  • Did you check this: https://stackoverflow.com/questions/44490627/how-to-import-export-a-class-in-vanilla-javascript-js – PepperoniSquat Jun 19 '23 at 13:02
  • Remove `src="Assets/testfunction.js"`. You can't have both `src` and body of the script – Konrad Jun 19 '23 at 13:03
  • Does this answer your question? [What does a script-Tag with src AND content mean?](https://stackoverflow.com/questions/6528325/what-does-a-script-tag-with-src-and-content-mean) – Konrad Jun 19 '23 at 13:04
  • So, after removing src, I get the error: "Loading module was blocked because of a disallowed MIME type" – Somecode Jun 20 '23 at 07:56

1 Answers1

0

Normally the error: "Loading module was blocked because of a disallowed MIME type" comes when you not define the file extension of file at the time of import.

wrong :

import foo from "./foo";

correct :

import foo from "./foo.js"

Your Code Runs Well in my browser

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script type="module">
        import pers from "./index.js";
         
        let p  = new pers("1", 1);
    
        alert(p.getAge());
        
    </script>
</body>
</html>

index.js

class Person2
{
    constructor(name, age) {
        this.name = name;
        this.age = age;
      }

      getName() {
        return this.name;
      }
      getAge() {
        return this.age;
      }
}

export default Person2;

Output image here

  • So after removing src, and adding type="module", I get the error: "Loading module was blocked because of a disallowed MIME type" – Somecode Jun 20 '23 at 07:57
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 21 '23 at 00:42