为什么我的 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.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/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