Use JS modules in HTML files
P粉301523298
P粉301523298 2023-09-07 14:46:07
0
1
606

Since I'm converting the Javascript code to node.js, I'm changing the old code to adapt it to ES6, using "Class< /strong>" and "Module" instead of just using the "Function" component.

I updated the server side first and everything went well. But now, I'm trying to get into the client and I'm having trouble converting the old encoding to the new one.

In the following example you can find 2 applets:

The "module" applet consists of 2 files: "FooClass.js" and "Foo_mod.html".

"Components" include "FooComp.js" and "Foo_comp.html".

All 4 files are stored in the same folder. Both applets should display an alert message "x = 7", but the "Module" applet does not, while the old fashion one Done right. However, when you press Ctrl and click the js file name in VS Code, there is no problem in reaching the js file from the html code. So there must be something wrong with my new code, but I can't find it. If anyone can help me, thanks in advance...

1 - Module-oriented applet (does not work):

FooClass.js:

class Foo {
    constructor() {
        this.foo = "";
    }
    cinq (x) {  //(real)->real
        return x + 5;
     }
}
module.exports = Foo;

Foo_mod.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page2</title>
</head>
<body>
    <script type="module" src="./FooClass.js"></script>
    <script type="text/javascript">
        var fx = new Foo();
        var x = fx.cinq(2);
        alert("x = " + x);  // must display "x=7"
    </script>
</body>
</html>

2 - Old method applet: (works fine)

FooComp.js

function cinq (x)  { //(real)->real
        return x + 5;
     }
// end of file FooComp.js

Foo_Comp.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>FooComp</title>
</head>
<body>
    <script type="text/javascript" src="./FooComp.js"></script>
    <script type="text/javascript">
        var y = 2;
        var x = cinq(y);
        alert("x = " + x);  // must display "x=7"
    </script>
    
</body>
</html>

P粉301523298
P粉301523298

reply all(1)
P粉674876385

You should modify the FooClass.js file to use the ES6 export syntax instead of module.exports:

export class Foo {
  constructor() {
    this.foo = "";
  }
  cinq(x) {
    return x + 5;
  }
}

You can use the import statement to import the Foo class:

<script type="module">
    import { Foo } from "./FooClass.js";
    var fx = new Foo();
    var x = fx.cinq(2);
    alert("x = " + x); // should display "x=7"
</script>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template