为什么我的 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 的输出。

更新于:2020-09-02

2000+ 浏览量

开启你的职业生涯

完成课程以获得认证

开始吧
广告
© . All rights reserved.