在 HTML 檔案中使用 JS 模組
P粉301523298
P粉301523298 2023-09-07 14:46:07
0
1
553

由於我要將Javascript 程式碼轉換為node.js,因此我正在更改舊程式碼以使其適應ES6,使用“Class< /strong>”和“模組”,而不是只使用“函數”元件。

我先更新了伺服器端,一切順利。但現在,我正在嘗試進入客戶端,但在將舊的編碼方式轉換為新的編碼方式時遇到了問題。

在以下範例中,您可以找到 2 個小程式:

「模組」小程式由 2 個檔案組成:「FooClass.js」和「Foo_mod.html」。

「元件」包括「FooComp.js」和「Foo_comp.html」。

所有 4 個檔案都儲存在同一資料夾中。 兩個小程式都應該顯示一條警報訊息“x = 7”,但“模組”小程式則不會,同時舊的時尚的人做得正確。 不過,在 VS Code 中按 Ctrl 點選 js 檔案名稱時,從 html 程式碼到達 js 檔案是沒有問題的。所以我的新程式碼肯定有錯誤,但我找不到它。如果有人可以幫助我,請先致謝...

1 - 以模組為導向的小程式(不起作用):

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 - 舊方法小程式:(工作正常)

#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

全部回覆(1)
P粉674876385

您應該修改 FooClass.js 檔案以使用 ES6 匯出語法而不是 module.exports

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

您可以使用import語句匯入#Foo類別:

<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>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!