為什麼我的 HTML 檔案無法從已獲取模組找到 JavaScript 函式?
如果未使用“export”語句,則可能發生這種情況。在要匯入到指令碼檔案中的函式前使用“export”。JavaScript 檔案如下,其檔名是 demo.js。
demo.js
console.log("function will import");
export function test(){
console.log("Imported!!!");
}以下是匯入以上函式的“index.html”檔案 −
index.html
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<script type='module'>
import { test } from "./demo.js"
test();
</script>
</body>
</html>要執行以上程式,請儲存檔名“anyName.html(index.html)”,然後右鍵單擊該檔案。在 VS Code 編輯器中選擇“使用 Live Server 開啟”選項。
下面是包含函式名 test() 的檔案 demo.js 的輸出。

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP